How to automatically restart Nginx when it goes down

Solution 1:

It is a feature of SystemD. Override existing unit file for NGINX by running systemctl edit nginx then paste in:



If NGINX is down due to, e.g. the OOM killer, it will be restarted after dying. If you have a configuration error in NGINX, it will not be restarted, of course.

To verify this configuration. start NGINX service with systemctl start nginx, and verify it is running with systemctl status nginx.

Kill it via pkill -f nginx. Confirm that NGINX is running anyway with systemctl status nginx.

Solution 2:

Use monit which purpose is to take care of situations like this.

apt install monit

nano /etc/monit/conf.d/nginx.conf

Put content below inside this file and restart monit

check process nginx with pidfile /var/run/
start program = "/usr/sbin/service nginx start"
stop program = "/usr/sbin/service nginx stop"

Solution 3:

You already have lots of answers how to do it, but I'd investigate what is happening to make it shut down in the first place, and fix that.

When nginx crashes, all currently running requests will be terminated in an unknown state -- files half-transferred, API calls unreplied. In principle the application on top should deal with this, in practice they seldom do, but at that layer it will manifest as weird and unreproducible behaviour, giving the people using the service an feeling of instability (and rightfully so).