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/

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


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

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

chmod +x /usr/local/bin/

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

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 "” 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/

*/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 write with pleasure on since 2006. You will find articles about operating systems written by me Windows, Linux, macOS, but also about web platforms such as WordPress and WooCommerce

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

Leave a Comment