DEV Community 👩‍💻👨‍💻

Gias Uddin
Gias Uddin

Posted on

How to set up an 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 the 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 web request with curl and check status code of response. If it is not 200 we will take recovery action i.e. reboot VM. You can take recovery action according your requirement. We will schedule this script on same machine as of web server.

Enter fullscreen mode Exit fullscreen mode

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

if [ "$status" -ne "200" ]
       # 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

Enter fullscreen mode Exit fullscreen mode

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/
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)

Take a look at this:


Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠