Shell Script To Auto Restart Apache HTTPD When it Goes Down / Dead

Here is a simple shell script tested on CentOS / RHEL / Fedora / Debian / Ubuntu Linux. Should work under any other UNIX liker operating system. It will check for httpd pid using pgrep command
pgrep command

pgrep looks through the currently running processes and lists the process IDs which matches the selection criteria to screen. If no process found it will simply return exit status 0 (zero).

Download the script and set cronjob as follows:

*/5 * * * * /path/to/script.sh >/dev/null 2>&1

Sample script

#!/bin/bash
# Apache Process Monitor
# Restart Apache Web Server When It Goes Down
# -------------------------------------------------------------------------
# RHEL / CentOS / Fedora Linux restart command
RESTART="/sbin/service httpd restart"

# uncomment if you are using Debian / Ubuntu Linux
#RESTART="/etc/init.d/apache2 restart"

#path to pgrep command
PGREP="/usr/bin/pgrep"

# Httpd daemon name,
# Under RHEL/CentOS/Fedora it is httpd
# Under Debian 4.x it is apache2
HTTPD="httpd"

# find httpd pid
$PGREP ${HTTPD}

if [ $? -ne 0 ] # if apache not running
then
 # restart apache
 $RESTART
fi



Comments

  1. Skrish October 30th

    Comment Arrow

    Is it possible to have a single script to monitor multiple services ?

    if so, drop me to skrish.040@gmail.com

    please


  2. Roger Stringer December 10th

    Comment Arrow

    You can copy the lines that mention httpd and change them to mention something else, so below the httpd check, copy the same lines and change the word “httpd” to “mysqld” and you are checking httpd and mysql


Add Yours

  • Author Avatar

    YOU


Comment Arrow



About Author

Roger Stringer

Code Monkey, web designer, web master, database guy, seo guy, author, chef, blogger, player of Warcraft and warhammer (when there's time).

I own various websites ranging from: Freekrai.net,Foodizu.com,DBStract.com and FoodJumper.com among others. I also blog regularly at RogerStringer.com and right here at The Dev Scene.