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:
#!/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:
#!/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:
That’s all. Using this method, you can restart any service. Thanks for reading. 🙂
*/5 * * * * /home/user/scripts/restart_mariadb.sh > /dev/null 2>&1