Automatically restart linux web services – nginx, mysql, php

 In Servers Admin, Servers Tutorials

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/startifdown.sh
4 – copy the bash code below to your script file “startifdown.sh”
5 – crontab -e
6 – Add the code at bottom (note this cron will run every 5m)

*/5 * * * * /opt/startifdown.sh >/dev/null 2>&1

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

The “startifdown.sh” file:

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

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.

Availability

  • August - Limited
  • September - Available
  • October - Available

Rates

  • My day rate is £300.
  • I can provide a fixed price for your work.
  • Projects start at around £2,000.

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.