web.onassar.com Archive

I can be reached at onassar@gmail.com.

For my open source work, check out github.com/onassar

Restart MySQL Automatically through a Cron Job

View more posts

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.

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

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).