Oliver Nassar

Restart Apache Automatically through a Cron Job

February 18, 2013

While it's indicative of other, larger, probems, my Apache server would at times crash. Rather, stop, and not respond. I believe this is related to memory/cpu problems with a cronjob I'm running. That aside, I wanted the server to automatically restart if it crashed, similar to my bash script/cronjob for restarting MySQL when it crashes.

I came up with the following, care of Stack Overflow:

if ! pgrep apache; then sudo /etc/init.d/apache2 restart; fi

I set that up by creating a file in my ~ directory named apache-check.sh, and pasting in:

#!/bin/bash
if ! pgrep apache; then sudo /etc/init.d/apache2 restart; fi

I had to give this file the proper permissions by running sudo chmod +x apache-check.sh, and then set that up in my crontab as follows:

* * * * * sh -x /home/ubuntu/apache-check.sh

This will run once a minute, restarting apache if it's not currently up.
Hope this helps someone.