Auto-restart MySQL & MySQL Router if it crashes

Auto-restart MySQL & MySQL Router 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

Here is also how to configure MySQL Router to auto-restart in case of failure using systemd:

nano /usr/lib/systemd/system/mysqlrouter.service

and add: Restart=on-failure right after the “ExecStart” line:

image 7 - Auto-restart MySQL & MySQL Router if it crashes

To make the changes take effect, systemd must be told to reload the unit files:

systemctl daemon-reload
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.