Script to Check MySQL is Running on Debian 9.5

Hello everyone, welcome to my blog. Today, I am going to show you a nice and pretty useful script that will check if the MySQL Server is running on Debian 9.5. This script is quite useful for website owners. Sometimes, the MySQL server is exited with status STOP or FAILED. If this happens, the website will be unavailable. You may notice the “ERROR ESTABLISHING A DATABASE CONNECTION” on your website. And it is BAD. It’s even worse if you do not set an email notification if your website is down. 

This script is very simple but useful. It will check the status of your MySQL server regularly and then if it is down or failed, this script will restart your MySQL server. 

Let’s create a new file called mysql_check.sh. I use nano, but you are free to use any text editor you like.

nano mysql_check.sh

And then copy and paste the following lines of code

#!/bin/bash
systemctl status mysql | grep "stopped\|dead\|failed"
if [ $? -eq 0 ]; then
echo "`date` - MySQL not running" 
systemctl restart mysql
else
echo "MySQL is up and running"
fi

Now close and save the file. Next, we need to make it executable

chmod +x mysql_check.sh

Done. Now we need to add a new cron job to execute this script every minute. You can change it to something else like every 5 minutes etc. 

nano /etc/crontab

Now add the following line at the bottom

*/1 * * * * root /root/./mysql_check.sh > /dev/null 2>&1

Change /root/mysql_check.sh with the actual location of the script. 

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.