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

When you have Linux servers with bases in administration, stopping for various reasons for mysqld is not a pleasant incident. In this tutorial you learn how to start mysql automatically if it stops for any reason, with the help of a script and Crontab.

I do not know what reasons for certain hours, the mysqld daemon stops suddenly without automatically restart. As the server logs did not help me much, I searched for a solution to check the running of the MySQLD service, and if it is not active, it will be started through a Crontab.

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

On MySQL servers with Madiadb, the MySQLD service should normally automatically restart when it stops for various reasons. If this does not happen, the script below will check periodically if Daemon MySqld runs and helps you start mysql if it is stopped.

My test is done on the operating system Debian 12, MariaDB 10.11.4.

1. Opens the console and creates the pitch for the future script that will start mysqld if it is stopped.

Eu prefer să folosesc editornano“.

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

2. În noul fișierautostart_mysql.shcopiază scriptul de mai jos:

#!/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. Salvați noul fișierautostart_mysql.sh, apoi setați permisiuni de executare.

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

4. Navigați în/usr/local/bin/și testați funcționarea scriptului prin comanda:./autostart_mysql.sh“.

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

At the moment, the script through which you start MySQL automat va rula numai atunci când este executat manual. Adăugat în crontab, acesta va rula periodic, la un interval de timp stabilit de noi. Eu am ales ca scriptulautostart_mysql.shsă fie rulat la fiecare 3 minute.

How do you add a script to Contab?

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

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

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

You save Crontab and leave the publisher.

After this step, checking 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 the comments.

Passionate about technology, I write with pleasure on stealthsetts.com starting with 2006. I have a rich experience in operating systems: Macos, Windows and Linux, but also in programming languages ​​and blogging platforms (WordPress) and for online stores (WooCommerce, Magento, Presashop).

Home Your source of IT tutorials, useful tips and news. How to start mysql automatically if it stops? [Linux]
Leave a Comment