This bash script is used to auto restart MySQL or MariaDB database if it crash/stop for any reason.
Create file
1 2 |
mkdir /usr/serverok vi /usr/serverok/mysql_monitor.sh |
Add
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#!/bin/bash # Author: ServerOK # Web: https://serverok.in/mysql-restart-bash MYSQL_USER="root" MYSQL_PASSWORD="YOUR_ROOT_PW_HERE" MYSQL_REPLY="$(mysqladmin -u ${MYSQL_USER} -p${MYSQL_PASSWORD} ping)" TIME_STAMP="$(date "+%Y-%m-%d %H:%M:%S")" if [[ ! "$MYSQL_REPLY" =~ "mysqld is alive" ]] then systemctl restart mariadb echo -e "${TIME_STAMP} MySQL Down\n" fi |
In the code, replace YOUR_ROOT_PW_HERE with your actual root password. If you are not using “root”, replace root with whatever username you use.
Make it executable
1 |
chmod 755 /usr/serverok/mysql_monitor.sh |
Create cronjob to run the script every 5 minutes.
1 |
crontab -e |
Add
1 |
*/5 * * * * /usr/serverok/mysql_monitor.sh > /var/log/sok-mysql.log |
See MySQL