Auto Restart MariaDB/MySQL If it Crashes on CentOS

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:

* * * * * /home/user/scripts/restart_mariadb.sh > /dev/null 2>&1

#or
* * * * * /bin/bash /home/user/scripts/restart_mariadb.sh > /dev/null 2>&1

That’s all. Using this method, you can restart any service. Thanks for reading.


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.