Automatically restart services and get notified

Mohammed Umrethwala · October 16, 2024

So you are running your own webserver which at the times is short of resources and the services like MySQL and HTTPD stop – resulting in your website being down until you get a chance to fix it. A quick solution would be to implement a script that will restart the service automatically and get notified with an email that services were restarted – so you can later go and check what was the problem

So below is the script, which will make sure that HTTP, MySQL, and Postfix are running all the time – It will check the status of the service and if it’s stopped or dead it will restart it.

How to Implement this Script?

Setup a cron to run the script every minute – like below.

* * * * * root /home/justgeek/scripts/servicecheck.sh

Create a file called servicecheck.sh and put the code below.
Just change the email address in the script to yours and you are done.

#!/bin/bash

#####################
#MySQL CHECK
#####################

/sbin/service mariadb status > /var/log/mysqlservicestatus 2>&1
STATUS=$(cat /var/log/mysqlservicestatus | egrep 'dead|failed')

        if [[ $STATUS = "" ]]
        then
/bin/logger -t MYSQL IS RUNNING
else
/sbin/service mariadb restart
/bin/logger -t restarted mysql
echo "Restarted MYSQL" | /bin/mail -s "Restarted MYSQL" you@email.com
fi
echo > /var/log/mysqlservicestatus

#####################
#HTTPD CHECK
#####################

/sbin/service httpd status > /var/log/httpdservicestatus 2>&1
STATUS=$(cat /var/log/httpdservicestatus | egrep 'dead|failed')

        if [[ $STATUS = "" ]]
        then
/bin/logger -t httpd IS RUNNING
else
/sbin/service httpd restart
/bin/logger -t restarted httpd
echo "Restarted HTTPD" | /bin/mail -s "Restarted HTTPD" you@email.com
fi

echo > /var/log/httpdservicestatus


#####################
#POSTFIX CHECK
#####################

/sbin/service postfix status > /var/log/postfixservicestatus 2>&1
STATUS=$(cat /var/log/postfixservicestatus | egrep 'dead|failed')

        if [[ $STATUS = "" ]]
        then
/bin/logger -t postfix IS RUNNING
else
/sbin/service postfix restart
/bin/logger -t restarted postfix
echo "Restarted postfix" | /bin/mail -s "Restarted postfix" you@email.com
fi

If you want to monitor other services, just go ahead and add them. All such posts are added in Scripting, In addition to this, I would also suggest you to make use of services like Uptimerobot to monitor your server in real time.

Twitter, Facebook