Personal tools
You are here: Home Blog Make sure Apache restarts after a crash

Make sure Apache restarts after a crash

Posted by lukepomfrey at Aug 18, 2008 11:10 AM |

A small Python script to make sure Apache never stays dead after a crash.

This morning I noticed that, at some point during the night, Apache had crashed and not restarted. To stop this happening again I decided to write a small Python script that would be run by cron to make sure Apache was running.

 

Here's the script:

apache_auto_restart

#!/usr/bin/env python
# Apache Auto Restarter

import os

def main():
   p = os.popen("/usr/bin/pgrep apache")
   out = p.read()
   p.close()
   if out == "":
      print "Apache2 not running...\n"
      print "Restarting..."
      rstart = os.popen("/etc/init.d/apache2 restart")
      output = rstart.read()
      rstart.close()
      print output
   else:
      print "Apache2 running already."
   return 0
if __name__ == '__main__': 
   main()

To have it run automatically every half hour, add the following to /etc/crontab:

0,30 * * * * root /path/to/apache_auto_restart >/dev/null 2>&1

There could probably be some error correction somewhere in it to make sure Apache has actually restarted but; a) it's a quick and dirty fix, b) I'm really lazy and c) I figure most people would probably notice if their server has been down for longer than half an hour or so and go and investigate.

Document Actions
  • Send this
  • Print this
  • Share this
Add comment

You can add a comment by filling out the form below. Plain text formatting.

Info
Note: you are not logged in. You may optionally enter your username and password below. If you don't enter your username and password below, this comment will be posted as the 'Anonymous User'.
(Required)
(Required)