How to Automatically Restart MySQL Server in the event of Crash?


MySQL server, due to complex configuration settings, sometimes crashes because of out-of-memory error. In such events, the process will die peacefully and the websites will go down until commands such as sudo service mysql start is issued.

In most cases, the websites can be restored by simply restarting the MySQL server and this could reduce a lot your website downtime.

Create a Shell Script

Create a script e.g.

1
2
touch check_mysql.sh
vim check_mysql.sh
touch check_mysql.sh
vim check_mysql.sh

It has the following content:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/bin/bash
 
TMP=`mysqladmin -u root -pPassword status 2>&1 | head -n 1 | cut -f1 -d:`
case ${TMP} in
Uptime)
        echo "MySQL is running."
        echo "You are good"
;;
*)
        service mysql restart
        # the following sends an email for notification, change email address if needed.
        echo "service mysql restart" | mail -s "service mysql restart" im@helloacm.com
        # the following triggers the Maker Event from IFTTT
        curl -X GET https://maker.ifttt.com/trigger/{MySQL}/with/key/KEY
;;
esac
#!/bin/bash

TMP=`mysqladmin -u root -pPassword status 2>&1 | head -n 1 | cut -f1 -d:`
case ${TMP} in
Uptime)
        echo "MySQL is running."
        echo "You are good"
;;
*)
        service mysql restart
        # the following sends an email for notification, change email address if needed.
        echo "service mysql restart" | mail -s "service mysql restart" [email protected]
        # the following triggers the Maker Event from IFTTT
        curl -X GET https://maker.ifttt.com/trigger/{MySQL}/with/key/KEY
;;
esac

This script checks the status of MySQL process and tries to restart the MySQL server. It also sends the email and triggers the Maker event (from IFTTT) which are optional.

Put this at Crontab

Make sure you add the script to the administrator (e.g. root)’s crontab job. Run crontab -e and add the following

1
*/5 * * * * * /var/www/check_mysql.sh > /dev/null 2>&1
*/5 * * * * * /var/www/check_mysql.sh > /dev/null 2>&1

In the example, the script is checked every 5 minutes.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
329 words
Last Post: How to Change the SwapFile Size at Linux?
Next Post: Using FluentAssertions Library to Write Better Unit Tests in .NET C#

The Permanent URL is: How to Automatically Restart MySQL Server in the event of Crash?

7 Comments

  1. eniel

Leave a Reply