Auto Restart MySQL if Crashed

This bash script is used to auto-restart MySQL or MariaDB database if it crashes or stops for any reason.

Create file

mkdir /usr/serverok
vi /usr/serverok/mysql_monitor.sh

Add

Advertisement

#!/bin/bash
# Author: ServerOK
# Web: https://serverok.in/mysql-restart-bash

MYSQL_REPLY="$(mysqladmin ping)"
TIME_STAMP="$(date "+%Y-%m-%d %H:%M:%S")"

if [[ ! "$MYSQL_REPLY" =~ "mysqld is alive" ]]
then
    systemctl restart mariadb
    echo -e "${TIME_STAMP} MySQL Down\n"
fi

In the code, replace YOUR_ROOT_PW_HERE with your actual root password. If you are not using “root”, replace root with whatever username you use.

Make it executable

chmod 755 /usr/serverok/mysql_monitor.sh

Create cronjob to run the script every 5 minutes.

crontab -e

Add

*/5 * * * * /usr/serverok/mysql_monitor.sh >> /var/log/sok-mysql.log
Add a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Advertisement