Problem

MySQL Database and MariaDB in CentOS and Ubuntu may crash and stop service when the server is out of memory resources. In such case, your web application would fail to work as it is able to access the database. e.g. In WordPress Website, it would display 「Error Establishing a Database Connection」.

Solution

First, we create a bash script file in the server with Linux command:

vim restart_db.sh

Then, we press 「i」 to write the bash script which check the status of the database and restart if it is not running:

#!/bin/bash

# Check if MariaDB is running
sudo systemctl status mariadb > /dev/null 2>&1
# Switch between the commands depending on the service and database you are using
# sudo service mysql status > /dev/null 2>&1

# Restart the MariaDB service if it's not running.
if [ $? != 0 ]; then
 sudo systemctl restart mariadb
 # Switch between the commands depending on the service and database you are using
 # sudo service mysql restart
fi

Press 「Esc」 to exit editing mode and type :w to write file. Type :q to quit the file after saving.

After that, we can setup a Cron Job in the terminal with the Linux command:

crontab -e

Press 「i」 to insert the following Cron Job statement on a new line:

* * * * * /bin/bash /root/restart_db.sh > /dev/null 2>&1

Press 「Esc」 to exit editing mode and type :w to write file. Type :q to quit the file after saving.

Then it is done. The Cron Job would run every 1 minute to check the status of the database and restart it if necessary.

# If you wish to run the cron job every 5 minutes
*/5 * * * * /bin/bash /root/restart_db.sh > /dev/null 2>&1
Related Keywords: Developer, How-to, Solved, Automatic Reboot, Linux Server Cronjob, Ubuntu, WordPress, Database Crash, MySQL / MariaDB die, Out of Memory, How-to, Solved