How to automate the startup of MySQL if it stops

When managing Linux database servers, the unexpected shutdown of the mysqld service can cause considerable inconvenience. In this tutorial, you'll see how to automate starting MySQL if it stops for various reasons using a script and crontab.

For unclear reasons, the mysqld daemon may stop suddenly and not restart automatically in certain situations or times. Since the server log files do not provide useful information in this regard, I looked for a solution to monitor the status of the mysqld service. Thus, in the situation where it is not active, the automatic restart should be initiated by means of a cronjob.

Let's see the step by step tutorial to solve this problem. (Tested on Linux Debian 12)

How to automate the startup of MySQL if it stops

The first step is to create the script that will restart the mysqld service if it is stopped.

1. Open a text editor (such as nano or vi) and copy the script below to a new file. For example, you can use:

nano /path/to/your/script.sh

Copy the script:

#!/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

Save and close the text editor.

2. Give execute rights to the script to make sure it can be run:

chmod +x /path/to/your/script.sh

3. Add the script below to the crontab (command: crontab -e allows you to edit):

*/3 * * * * /path/to/your/script.sh

The above line specifies that the script will be run every 3 minutes. symbol */3 means "every 3 minutes". Basically, with this line you automate starting MySQL with script.sh.

4. Save and close the file crontab.

Now, your script script.sh will be run automatically every 3 minutes to check service status mysqld and restart it if necessary.

If something goes wrong and you need help, we are happy to answer your comments.

Technology enthusiast, I enjoy writing tutorials and helpful guides for operating systems, hardware systems, programming languages, and mobile phones (iOS, Android). I love to experiment and discover new SEO techniques and web optimization strategies.

Home » Smart tutorial » How to automate the startup of MySQL if it stops
Leave a Comment