Automatically restart linux web services - nginx, mysql, php
  • LET'S TALK!

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

  • This field is for validation purposes and should be left unchanged.

Freelance WordPress Developer

Automatically restart linux web services – nginx, mysql, php

Shell Script to Restart the Services if Down/Crashed

It’s common for the 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 freeway – 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 as postfix dovecot and others, just remember to close the statement with “fi”.

Download full script here.

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

ABOUT AUTHOR

Nuno

Hi, I'm 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.