How to automatically start MySQL if it stops? [Linux]

When managing Linux servers with databases, the sudden shutdown of the mysqld service for various reasons is not a pleasant incident. In this tutorial, you will learn how to automatically start MySQL if it stops for any reason using a script and crontab.

For some unknown reasons, at certain times, the mysqld daemon abruptly stops without restarting automatically. Since the server logs didn't provide much help, I looked for a solution to check the status of the mysqld service and, if it's not active, start it using a crontab.

How to automatically start MySQL if it stops? [Linux]

On MySQL servers with MadiaDB, the mysqld service should normally restart automatically when it stops for various reasons. If this doesn't happen, the script below will periodically check if daemon mysqld runs and helps you start MySQL automatically if it is stopped.

My test is done on OS Debian 12, MariaDB 10.11.4.

1. Open the console and create the file for the future script that will start the mysqld service if it is stopped.

I prefer to use editor "nano".

sudo nano /usr/local/bin/autostart_mysql.sh

2. In the new file “autostart_mysql.sh” copy the script below:

#!/bin/bash

if systemctl is-active mysqld > /dev/null; then
  echo "The mysqld service is running."
else
  echo "The mysqld service is not running. Restarting..."
  systemctl start mysqld
fi

3. Save the new file “autostart_mysql.sh“, then set execute permissions.

chmod +x /usr/local/bin/autostart_mysql.sh

4. Navigate to “/usr/local/bin/” and test the script by command: “./autostart_mysql.sh".

How to automatically start MySQL if it stops? [Linux]
Autostart mysql service

Right now, the script you're starting from MySQL automatically will only run when manually executed. Added to the crontab, it will run periodically, at a time interval set by us. I chose that the script "autostart_mysql.sh” to be run every 3 minutes.

How do you add a script to crontab?

To add a script to the crontab to run periodically, at a time interval set by you, run the command: crontab -e, then add the command line to the end of the file.

*/3 * * * * /usr/local/bin/autostart_mysql.sh

*/3 specifies that the script will be executed every 3 minutes.

Save the crontab and exit the editor.

After this step, check the service mysqld it will be done every 3 minutes, and if the service is stopped, it will be started automatically.

If you need help or other clarifications, we are happy to answer your comments.

Passionate about technology, I enjoy writing on StealthSettings.com since 2006. I have a rich experience in operating systems: macOS, Windows, and Linux, as well as in programming languages and blogging platforms (WordPress) and for online stores (WooCommerce, Magento, PrestaShop).

How to » Linux » MySQL » How to automatically start MySQL if it stops? [Linux]
Leave a Comment