Cover Image by MilesAndryPrower on DeviantArt
Cover Image by MilesAndryPrower on DeviantArt

Auto-restart MySQL if it crashes

Here is a small script that will restart the MySQL service in case it crashes.

* * * * * /sbin/service mysql status || service mysql start

Add it to /etc/crontab to run every minute.


More complex script that does the same thing 😀

#!/bin/sh

while [ "1" -eq "1" ]; do

ERR=1
if [ -f /var/lib/mysql/mysql.sock ]; then
    kill -0 `cat /var/lib/mysql/mysql.sock` 2>/dev/null
    ERR=$?
fi

if [ $ERR -ne 0 ]; then
    sleep 10
    if [ -f /var/lib/mysql/mysql.sock ]; then
        kill -0 `cat /var/lib/mysql/mysql.sock` 2>/dev/null
        ERR=$?
    fi
fi

if [ $ERR -ne 0 ]; then
    if [ -f /usr/sbin/service ]; then
        /usr/sbin/service mysqld start
    else
        if [ -f /sbin/service ]; then
            /sbin/service mysqld start
        else
            service mysqld start
        fi
    fi
fi
sleep 2

done
whoami
Stefan Pejcic
Join the discussion

I enjoy constructive responses and professional comments to my posts, and invite anyone to comment or link to my site.