How to set up a live-saving automatic restart script for your web server

How to set up a live-saving automatic restart script for your web server

If your web server crashes, it can be extremely frustrating. Not only is your website down, but you also have to go through the process of restarting the server. This can be time-consuming and difficult, especially if you're not familiar with server administration.

However, there is a way to automatically restart your web server after a crash. With a few simple steps, you can set up a script that will check if your server is down and, if it is, restart it. This way, you can focus on other things and know that your website will be back up and running as soon as possible.

Building Crash Detection and Recovery Script

Below we will make a web request with curl and check the status code of the response. If it is not 200 we will take recovery action i.e. reboot VM. You can take recovery action according to your requirement. We will schedule this script on the same machine as of web server.

                **auto_recover_script.sh**
#!/bin/bash

status=`curl -s -o /dev/null -w "%{http_code}" https://giasuddin.com`
echo `date` $status >> crash_checks.log

if [ "$status" -ne "200" ]
then
       # Take any appropriate recovery action here.
    echo "webserver seems down, initiating reboot." >> check.log
    # start your application 
        # or Do what type of action you need, you restart 
        yourapplication again

fi

Additional Setting

Open crontab in edit mode to create cronjob.

$ crontab -e Schedule web application auto restart and crash detection script.


# To trigger crash detection script after every 5 minutes
*/5 * * * * sh /path/to/script/auto_recover_script.sh

Conclusion We learned how to write a custom script to detect and recover web applications when the web server goes down unexpectedly. This technique helps us maintain high availability despite web server crashes. Though this script is useful, we should always try to find the actual cause of the crash and fix it accordingly.

Did you find this article valuable?

Support Giasuddin Blog by becoming a sponsor. Any amount is appreciated!