Auto-Restart MariaDB When It Crashes
During a brute force attempt, running on a low-memory virtual private server (VPS) can cause
mariadb to crash and render your websites unusable.
The most fruitful solution is to permanently increase your VPS’s memory, but I can understand that administrators refuse to pay for resources that are otherwise never utilized during normal operation. To keep things up and running automatically after a crash, I use a simple cronjob to check and restart
mariadb if it is down.
Load the crontab editor in the terminal with
crontab -e and add the following line:
* * * * * systemctl status mariadb.service > /dev/null || systemctl start mariadb.service
This checks if MySQL is running every minute and redirects stdout to null.
Starting the service will not output anything unless something goes wrong, so there is no need to add the null redirect on the last command. The double pipe
OR and will execute the second command only if the first command fails. In other words: if MySQL’s status returns an exit code greater than zero (first command), start MySQL (second command).
View your crontab