Post

Configure Nginx To Automatically Restart On Ubuntu

If Nginx process is dies, you can run following command to restart it.

1
sudo systemctl restart nginx

What if you’re sleeping?

We can have Nginx automatically restart! To override the default systemd service configuration, we will create a new configuration directory.

1
sudo mkdir -p /etc/systemd/system/nginx.service.d/

The -p flag will create nested directories if they don’t exist already.

Then create the following file.

1
sudo vi /etc/systemd/system/nginx.service.d/restart.conf

Add the following lines to the file. These lines tell Nginx to automatically restart 5 seconds after detecting a failure.

1
2
3
[Service]
Restart=on-failure
RestartSec=5s

For additional options, you can visit the man page.

From the man pages: Exit causes and the effect of the Restart= settings From the man pages: Exit causes and the effect of the Restart= settings

Reload systemd for the changes to take effect.

1
sudo systemctl daemon-reload

To verify this change is working, kill Nginx with:

1
sudo kill -9 nginx

As that other guy said: “kill -9 is the unsafe way of brutally murdering a process. It’s equivalent to pulling the power cord, and may cause data corruption.”

Check Nginx status.

1
ps aux | grep nginx

Now try it with kill -15

1
sudo kill -15 nginx

Recheck Nginx status. You will find Nginx automatically restarted the first time but not the second.

1
ps aux | grep nginx

systemctl status nginx

Have fun!

This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.

© Kevin Schwickrath. Some rights reserved.

Using the Chirpy theme for Jekyll.