Ubuntu

Configure Nginx To Automatically Restart On Ubuntu

Posted February 10, 2024

By Kevin Schwickrath1 min read

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

Terminal window
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.

Terminal window
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.

Terminal window
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.

[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.

Terminal window
sudo systemctl daemon-reload

To verify this change is working, kill Nginx with:

Terminal window
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.

Terminal window
ps aux | grep nginx

Now try it with kill -15

Terminal window
sudo kill -15 nginx

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

Terminal window
ps aux | grep nginx

systemctl status nginx

Have fun!

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