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>&

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)

ABOUT AUTHOR

Nuno

I am a Freelance Web Developer and WordPress Expert based in London with a wealth of website development and support experience. I am great at problem solving and developing quick solutions.

LEAVE A COMMENT

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.

  • LET'S TALK!

    Fill in the form below to make an enquiry or find my contact details on my contact page.

  • This form collects your name and email address 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.