If not managed properly, unexpected database crash happens often on a VPS.
In this short tutorial, we'll discus about how to fail-safe the MySQL, MariaDB server, or any other database server like PostgreSQL on Linux platforms.
What's the plan?
First we've to check if the database server is running or not at all. The simplest method to determine this will be to check the PID of the database server, with the pidof
linux command.
After that we'll construct a single line of shell script to check the PID, if the PID is null, then start the database server with the systemctl
command. The example script below.
if [ -z $(pidof mysqld) ]; then systemctl start mariadb.service; fi
If you're familiar with Linux shell scripting, the script above is pretty self explanatory.
Finally add a cron job for the root user, that runs every minute, executing the script above.
sudo crontab -e
*/1 * * * * if [ -z $(pidof mysqld) ]; then systemctl start mariadb.service; fi
You may need to change the systemd service name, as I'm using mariadb.service
here, you may have the mysql.service
installed.
Here's the final result, a screenshot from a production server, now PHP based app is up within a minute even after a database crash.
Thoughts and Conclusion
So, that's all you need to do, to autostart the MySQL server after a crash. In fact the same method could be used for any other application or database server.
Just change the systemd service name and you're good to go most of the times, unless the app require some special condition to start.
Indeed it's not the only way to do that, if you've some better idea, please share in the comments.
Leave a Reply