Managing the availability of your MySQL database is critical for uninterrupted service. In the event that your MySQL server unexpectedly stops, whether due to system issues or any other reason, it's essential to have a mechanism in place to automatically restart it. This blog post will guide you through the process of creating a shell script and setting up a Systemd service that monitors MySQL's status and automatically restarts it if it's not running. These instructions are applicable to Ubuntu, Debian, and CentOS Linux distributions.
[Step 1: Login to the Terminal]
Access your server's terminal by logging in as a superuser (root) with the following commands:
sudo su
You'll be prompted for your system password (Enter with your System password).
[Step 2: Create a Shell Script to Restart MySQL]
Create a shell script named `restart_mysql.sh` and open it for editing:
nano /usr/local/bin/restart_mysql.sh
Add the following content to the file:
#!/bin/bash
while true; do
if ! systemctl is-active --quiet mysql; then
echo "MySQL is not running. Restarting..."
/etc/init.d/mysql start
fi
sleep 5
done
Save the file. its looks like below image
[Step 3: Make the Script Executable]
Make the script executable with the following command:
chmod +x /usr/local/bin/restart_mysql.sh
[Step 4: Create a Systemd Service]
Create a Systemd service file named `mysql_restart.service` and open it for editing:
nano /etc/systemd/system/mysql_restart.service
Add the following content to the file:
[Unit]
Description=MySQL Restart Service
After=network.target
[Service]
ExecStart=/usr/local/bin/restart_mysql.sh
Restart=always
User=root
Group=root
[Install]
WantedBy=multi-user.target
Save the file. its looks like below image
[Step 5: Enable and Start the Service]
Enable the newly created service and start it:
sudo systemctl enable mysql_restart.service
sudo systemctl start mysql_restart.service
[Step 6: Check the Status of the Service]
You can check the status of the MySQL restart service using the following command:
sudo systemctl status mysql_restart.service
This command will display information about the service, including whether it's active and running.
*** THE END ***
By following these steps, you will have set up an automatic MySQL restart mechanism on your Ubuntu, Debian, or CentOS server, ensuring that your MySQL database restarts seamlessly whenever it unexpectedly stops, thereby maintaining uninterrupted database operations.
No comments:
Post a Comment