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.
content
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.
I prefer to use editor ”nano
“.
sudo nano /usr/local/bin/autostart_mysql.sh
2. In the new file ”autostart_mysql.sh
"Copies 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 execution permits.
chmod +x /usr/local/bin/autostart_mysql.sh
4. Navigate in “/usr/local/bin/
"And test the operation of the script by command:"./autostart_mysql.sh
“.
![How to start mysql automatically if it stops? [Linux]](https://stealthsettings.com/wp-content/uploads/2023/11/Autostart-mysql-service.webp)
At the moment, the script through which you start MySQL Automatically will run only when executed manually. Added in Crontab, it will run periodically, at a time period established by us. I chose the script ”autostart_mysql.sh
"Be rolled every 3 minutes.
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.