Thursday, April 16, 2015

Restart Apache Automatically

Recently the apache httpd server on one of the projects we run has taken to segfaulting randomly a couple times a week. While we try to gather some more information about what's going on, we've been using a quick one-liner cron job to check every minute that the apache process is still running, and start it back up if it's dead. On ubuntu, it's just a matter of dropping a one-line file with the following into /etc/cron.d (like say as /etc/cron.d/restart-apache-automatically):

* * * * * root pgrep apache2 >/dev/null || service apache2 start

We don't redirect the output of the start command so that it will automatically send mail to root whenever it restarts (but if you don't want it to send mail, you might instead send the output to a custom logfile, like say service apache2 start >>/var/log/apache2/restart.log 2>&1). Also, on some more traditional linuxes, you might instead add this one line to the root user's crontab, looking for a process named httpd instead of apache2, like this:

* * * * * pgrep httpd >/dev/null || /etc/init.d/httpd start

Of course if we were using systemd or some other process supervisor, we could just skip this cron business altogether and simply configure the service to restart automatically (like with Restart=on-failure in systemd's httpd.service config file).