Use a script to automatically restart Apache when it fails

  • 2020-05-10 23:17:19
  • OfStack

I don't know why my blog has been hanging up lately,

Just restart Apache and I won't bother to find out what went wrong.

But every time you need to manually go up SSH and restart Apache, it's a bit troublesome.

And sometimes you die at night, and you can't even access the blog at night.

Finally, I couldn't stand it anymore and wrote a script to do it. The code is as follows:


#!/bin/sh
if ( wget --timeout=5 -q --spider http://leonax.net/ )
then
echo "ok"
else
/etc/init.d/httpd restart
echo "httpd restarted"
fi

The idea is simple, just try to access 1 blog (line 3),
If there is a problem, restart Apache (line 7).
The parameter of wget, the wok.
If you like, you can also add a piece of email code to else,
Send Apache error log directly to email for easy analysis, but I am too lazy to do it.

Then save this code as check_apache.sh and add it to crontab:


*/5 * * * * /var/www/check_apache.sh

Where */5 represents 1 run every 5 minutes for check_apache.sh.
Note that sudo is used when opening crontab, because restarting Apache requires sudo permissions.

This is a very useful little feature for those of you who use Linux


Related articles: