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 a 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 15 minutes (you can adjust the interval time) and will start if found not running.

Auto-restart MySQL, PHP-FPM, Nginx if down

  • Create a file using vi editors at your desired location.
  • Copy & paste below script to the file and save it.

#!/bin/bash
#Scripts to start services if not running
ps -ef | grep nginx |grep -v grep > /dev/null
if [ $? != 0 ]
then
       systemctl restart nginx.service > /dev/null
fi
ps -ef | grep php-fpm |grep -v grep > /dev/null
if [ $? != 0 ]
then
       systemctl restart php7.2-fpm.service > /dev/null
fi
ps -ef | grep mysql |grep -v grep > /dev/null
if [ $? != 0 ]
then
       systemctl restart mysql.service > /dev/null
fi

  • Change the file permission to be executable
chmod 755 restart.sh

Test it manually to ensure the script is executable.

You can put this in cron to run every 15 minutes.

crontab -e

the put the following line:

*/1 * * * * /opt/restart.sh