How to automatically restart Nginx

Published by Igor Khrupin on

Here is instruction how to launch Nginx server after close unexpectedly.

1. Create /root/ file with next content:

if [[ ! "$(/etc/init.d/nginx status)" =~ "active (running)" ]]
    echo $(date -u) "NGINX server has been stopped. It has now been restarted."
    service nginx start

2. Make it executable chmod +x /root/
3. sudo crontab -e
4. Add crontab job. For 3 min period job will be next:

*/3 * * * * /root/ >> /var/log/nginxfix.log 2>&1

/var/log/nginxfix.log – log file

Let me know better approach in comments.


T S.N · 15 February, 2020 at 14:14

*/3 * * * * pgrep nginx > /dev/null || /etc/init.d/nginx restart

Tariq · 10 May, 2020 at 22:29


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.

Leave a Reply to T S.N Cancel reply

Avatar placeholder

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.