Table of Contents
This article will introduce you to a script that automatically check the nginx service and restart if the nginx service failed.
Everyone knows nginx is a popular web server with incredible power.
What all system administrators care about is that if the nginx service is failed in the middle of the night. So, what to do?
You will need an automated script to do something.
Script automatically check nginx service and restart
I wrote a simple script during my work.
About the script
First, I have to say that this script I wrote for CentOS 6. You can change it a bit for your system, it’s quite easy.

Most of the time I work with nginx, I see there are times when the nginx service is not working. Cause, depending on circumstances, the server may be overloaded RAM.
Recommended Reading: Script automatically frees up memory
My script does the following:
- Get the current status of nginx service.
- Check if the status is not running, immediately restart the service. Send alert email to admin.
- If restart the service failed and status services is
nginx dead but subsys locked,then delete the subsys locked file and restart nginx. Send alert email to admin.
Note the change in the script
In the script, before you use it, you need to change some information in it.
- [email protected]: change to the email address you use to send email.
- [email protected]: change to your first administrator’s email address.
- [email protected]: change to your second administrator’s email address. If there is only one administrator, just delete this email address in the script.
And one more thing, the script uses mail command to send alert emails. Please use the command below to check if it exists or not.
mail --helpIf not, install the mailx package.
yum install mailx -yDownload and use script
Recommended Reading: Script free disk space from deleted files
First, use the following command to download the script to the server, put the script in the /opt directory.
wget https://gitlab.com/Danny_Pham/WriteBash.com/raw/master/Utilities/07-Script_auto_restart_nginx.sh -O /opt/script_auto_restart_nginx.shThen you assign the executable permissions to the script.
chmod 0700 /opt/script_auto_restart_nginx.shYou already have the script, now how to make it run automatically, we must use crontab.
Use the command below to add crontab.
crontab -l | { cat; echo "# Check nginx service every 1 minute & auto restart service if it's failed"; } | crontab -
crontab -l | { cat; echo "*/1 * * * * /opt/script_auto_restart_nginx.sh"; } | crontab -Conclusion
So, you have a simple tool to track nginx service. If at some point, it doesn’t work, you don’t have to worry.
The script will automatically do its job, restart the nginx service if checking that status is not running. It is very simple but very useful in your work.
(This is an article from my old blog that has been inactive for a long time, I don’t want to throw it away so I will keep it and hope it helps someone).