Oliver Nassar

Restart MySQL Automatically through a Cron Job

February 06, 2013

I was running into a problem with my production server's MySQL install. Every couple months, MySQL would bail. I'm not sure why. It would stop, rather than restart.

It was pretty easy to diagnose, but a hastle since I wouldn't be alerted of it immediately, especially if I wasn't close to a computer.

I put together the following shell script to restart MySQL if it's not on.

#!/bin/bash
/usr/bin/mysqladmin ping| grep 'mysqld is alive' > /dev/null 2>&1
if [ $? != 0 ]
then
    sudo service mysql restart
fi

Works super well.
To make it executable, I had to run: chmod 0755 mysql-check.sh
Following this, I added it to my Ubuntu crontab with: * * * * * sh -x /home/onassar/mysql-check.sh

This will run the script every minute, and check if MySQL is running properly. If not, it is restarted (rather than started).