Auto Restart MariaDB/MySQL If it Crashes on CentOS

Published on May 23, 2021 36 sec read

Infrequently it happens on CentOS. MySQL/MariaDB stops working and our web application crashes. At this situation we have to login to SSH and restart MySQL/MariaDB server. It’s a painful thing.

To get rid of this issue, we can create a script to check database service is running or not. If database service stops, the script will restart the service automatically.

Have a look at the bash script to restart MySQL:

restart_mysql.sh
#!/bin/bash

# Check if MySQL is running
sudo systemctl status mysql > /dev/null 2>&1

# Restart the MySQL service if it's not running.
if [ $? != 0 ]; then
    sudo systemctl restart mysql
fi

Have a look at the bash script to restart MariaDB:

restart_mariadb.sh
#!/bin/bash

# Check if MariaDB is running
sudo systemctl status mariadb > /dev/null 2>&1

# Restart the MariaDB service if it's not running.
if [ $? != 0 ]; then
    sudo systemctl restart mariadb
fi

After that add a cronjob like this:

*/5 * * * * /home/user/scripts/restart_mariadb.sh > /dev/null 2>&1
That’s all. Using this method, you can restart any service. Thanks for reading. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.
Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow