DEV Community

Gias Uddin
Gias Uddin

Posted on • Edited 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.

                **auto_recover_script.sh**
Enter fullscreen mode Exit fullscreen mode
#!/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
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/auto_recover_script.sh
Enter fullscreen mode Exit fullscreen mode

Conclusion
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.

Thank you for reading my article! If you enjoyed it and would like to support my work, please consider buying me a coffee at Buy Me a Coffee. You can also learn more about me and my work by visiting my Giasuddin Bio and following me on LinkedIn and Twitter. Thank you for your support!

Top comments (0)