Automatically detecting server downtime using Linux cron job

If you run a website, you may have experienced some down time. Occasionally, the web server can go down. It would be great if we can get an email when the server is down.

We can easily schedule a Linux job which periodically checks the status of the website and sends an email when there is an issue. This post shows how to create a Linux cronjob to detect website downtime and send an email.

Step 1: Create a script file named “downtime_detector.sh”.

You can create the file under your home directory. Copy the following text to the created script file.

if curl -s "http://www.programcreek.com/2016/08/leetcode-russian-doll-envelopes-java/" | grep -q "Russian Doll Envelopes"
then
    # if the keyword is in the content
    echo " the website is working fine"
else
    echo "Program Creek Error" | /usr/sbin/sendmail [email protected]
fi

The script checks if the target web page contains the string “Russian Doll Envelopes”. If the page contains the string, the page is rendered correctly. If not, a message will be sent to an email address.

Step 2: Install “sendmail” on your Linux machine.

“sendmail” is a popular and reliable tool that can be easily setup to send emails under Linux.

sudo apt-get install sendmail

Step 3: Create a cronjob.

Type “crontab -e” to edit the cronjob list.

Append the following line:

*/5 * * * * /path/to/script/downtime_detector.sh

That’s it. Comparing to other online downtime detection services, this method is pretty flexible and you can change it to whatever you like it to be. This method does not require an extra server, but having a separate server is better in case the server is completely down in which case the detection script does not run at all.

Leave a Comment