Nginx – Run a shellscript if nginx encounter an error

nginxspawn-fcgi

can I config my nginx to run some shell command/script if encounter 5xx error?

My spawn-fcgi crashes often, I have a cronjob restart it periodically, but I think the best solution would be if nginx fail to reach spawn-fcgi then restart it via command.

Best Answer

You could run monit doing like this in the config:


check process spawn-fcgi with pidfile /var/run/spawn-fcgi.pid
        start program = "/etc/init.d/spawn-fcgi start"
        stop program = "/etc/init.d/spawn-fcgi stop"
        if failed host localhost port 80 protocol HTTP request /test.php then restart
        if 5 restarts within 5 cycles then timeout
        depends on nginx

check process nginx with pidfile /var/run/nginx.pid
        start program = "/etc/init.d/nginx start"
        stop program = "/etc/init.d/nginx stop"
        if failed host localhost port 80 protocol HTTP request /token.html then restart
        if 5 restarts within 5 cycles then timeout

the test.php is just a php file that does echo 'OK'

Of course I supose you already have a spawn-fcgi init script and a PID file.