Cron job script to Restart MySQL / MariaDB server when it stops accidentally

How to Stop Mariadb Server:

systemctl start mariadb.service
systemctl enable mariadb.service

You can check to see if mariadb is running by executing the following command:

systemctl is-active mariadb.service

This will show "Active" or "inactive" depending on status of mariadb server.

Script for checking mariadb status and restarting if it is inactive:

#!/bin/bash
if [[ ! "$(systemctl is-active mariadb.service )" =~ "active" ]]
then
    systemctl start mariadb.service
fi

You can add this script as a cron Job.

e.g. Put an entery in crontab using:

sudo crontab -e
*/1 * * * * /var/www/scripts/mysql-check.sh
You can see I have enabled checking every minute for mariadb server. So even if mysql goes down due to any cause it will be restarted within minute. !
 
So enjoy and Happy Coding ;-)
 
Note:- For another MySQL server I used following script:-
 
#!/bin/bash
if [[ ! "$(/usr/sbin/service mysql status)" =~ "SUCCESS! MySQL running" ]]
then
  /usr/sbin/service mysql restart
  echo "done restarting service"
fi