Automatically restart linux web services – nginx, mysql, php

 In All, Servers

Automatically restart linux web services – nginx, mysql, php

Shell Script to Restart the Services if Down/Crashed

It’s common for process to crash/go down due to various reasons, which you can investigate and fix the issues but that may take little time. However, one thing you can do it immediately to reduce the downtime for better availability is to automate restart of the process if it’s down.

Let’s get this done through the free way – shell scripts

You can use following shell scripts to run through crontab, which will check the services at every 5 minutes (you can adjust the interval time) and will start if found not running. Sounds cool?

Make the script steps:

1 – update-rc.d cron defaults
2 – /etc/init.d/cron start
3 – nano /opt/
4 – copy the bash code below to your script file “”
5 – crontab -e
6 – Add the code at bottom (note this cron will run every 5m)

*/5 * * * * /opt/ >/dev/null 2>&1

7 – Be sure the scrip is executable: chmod +x /opt/

The “” file:

#Scripts to start services if not running
ps -ef | grep nginx |grep -v grep > /dev/null
if [ $? != 0 ]
/etc/init.d/nginx start > /dev/null
ps -ef | grep php5-fpm |grep -v grep > /dev/null
if [ $? != 0 ]
/etc/init.d/php5-fpm start > /dev/null
ps -ef | grep mysql |grep -v grep > /dev/null
if [ $? != 0 ]
/etc/init.d/mysql start > /dev/null

You can adjust the script to add other services such postfix dovecot and others, just remember to close the statement with “fi”.

Download full script here.

Thank you for seeing my tutorial and fell free to share and comment 🙂 . Do you have a code snippet and you want to see it publish on my site ? I will be more than happy to do it please send me a message (here)

Recent Posts

Leave a Comment

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

Start typing and press Enter to search

Let's work together

I'd love to work with you! Please fill out my project form to tell me more about your project/work. I reply to all enquiries within 48 hours.


  • November - Booked
  • December - Booked
  • January - Available


  • My day rate is £300.
  • I can provide a fixed price for your work.

EN - Header Enquiry Form

  • This form collects your name, email address and telephone number so that I can respond to the enquiry(ies) that you submit via this website. Please check my privacy policy for the full story on how I use, protect and manage your submitted data.