Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Script to automatically relaunch Nginx and MySQL servers
#!/bin/bash
#settings
EMAIL="me@example.com"
SUBJECT="THE EMAIL SUBJECT"
# date
DATETIME=$(date +%F_%T)
DATE=$(date +"%Y-%m-%d")
# test nginx
function check_for_nginx() {
if [[ ! "$(/usr/sbin/service nginx status)" =~ "is running" ]]
then
echo "$DATETIME : restarting nginx..."
/usr/sbin/service nginx start
echo "Nginx server has been restarted: $DATETIME." | mail -s "$SUBJECT NGINX RESTARTED" "$EMAIL"
else
echo "$DATETIME : nginx is running"
fi
}
# test apache
function check_for_apache() {
if [[ ! "$(/usr/sbin/service apache2 status)" =~ "is running" ]]
then
echo "$DATETIME : restarting apache..."
/usr/sbin/service apache2 start
echo "Apache server has been restarted: $DATETIME." | mail -s "$SUBJECT APACHE RESTARTED" "$EMAIL"
else
echo "$DATETIME : apache is running"
fi
}
# test mysql
function check_for_mysql_old() {
if [[ ! "$(/usr/sbin/service mysql status)" =~ "start/running" ]]
then
echo "$DATETIME : restarting mysql..."
/usr/sbin/service mysql start
echo "MySQL server has been restarted: $DATETIME." | mail -s "$SUBJECT MYSQL RESTARTED" "$EMAIL"
else
echo "$DATETIME : mysql is running"
fi
}
# test mysql
function check_for_mysql() {
UP=$(pgrep mysql | wc -l);
if [ "$UP" -eq 0 ];
then
echo "$DATETIME : restarting mysql..."
/usr/sbin/service mysql start
echo "MySQL server has been restarted: $DATETIME." | mail -s "$SUBJECT MYSQL RESTARTED" "$EMAIL"
else
echo "$DATETIME : mysql is running"
fi
}
function lets_do_it_now() {
# check_for_nginx
check_for_apache
check_for_mysql
}
# We have everything, let's do it.
lets_do_it_now
@mikedamoiseau

This comment has been minimized.

Copy link
Owner Author

@mikedamoiseau mikedamoiseau commented Mar 30, 2017

Add the script to the cronjob with the command crontab -e:

*/10 * * * * /root/relaunch-services.sh >> /root/relaunch-services.log 2>&1

This will execute the script every 10 minutes and redirect the output to the log file (stdout and stderr)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment