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

  1. #!/bin/bash
  2. # Apache Process Monitor
  3. # Restart Apache Web Server When It Goes Down
  4. # -------------------------------------------------------------------------
  5. # Copyright (c) 2003 nixCraft project <http://cyberciti.biz/fb/>
  6. # This script is licensed under GNU GPL version 2.0 or above
  7. # -------------------------------------------------------------------------
  8. # This script is part of nixCraft shell script collection (NSSC)
  9. # Visit http://bash.cyberciti.biz/ for more information.
  10. # -------------------------------------------------------------------------
  11. # RHEL / CentOS / Fedora Linux restart command
  12. RESTART="/sbin/service httpd restart"
  13.  
  14. # uncomment if you are using Debian / Ubuntu Linux
  15. #RESTART="/etc/init.d/apache2 restart"
  16.  
  17. #path to pgrep command
  18. PGREP="/usr/bin/pgrep"
  19.  
  20. # Httpd daemon name,
  21. # Under RHEL/CentOS/Fedora it is httpd
  22. # Under Debian 4.x it is apache2
  23. HTTPD="httpd"
  24.  
  25. # find httpd pid
  26. $PGREP ${HTTPD}
  27.  
  28. if [ $? -ne 0 ] # if apache not running
  29. then
  30. # restart apache
  31. $RESTART
  32. fi
A better and more reliable solution is monit monitoring software for restarting services such as mysql, apache and sendmail under UNIX / Linux operating systems.

Post a Comment