Naser Sobhan

Accomplished Software Engineer and Solution Architect

  • Home

Simple Bash Script to Restart Apache when it fails

25/06/2019

I should say I have no Idea why Apache fails a lot (sometimes looks like for no reason) maybe huge loads of Users or other things.

Server admins can’t monitor the server all the time 24/7, I know there are lots of Monitoring Applications and services but if you want a good one you have to pay alot.

but suddenly I found this script which saved my life for free

#!/bin/bash
echo "checking Webserver..." 
    # 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
    	echo "Webserver down"
	 	# restart apache
 		
        #mail -s "Server Is down" "[email protected]" "Apache is Down, trying to Restart!"
		#echo "mail sent!"
        $RESTART
	fi

this code is life saver, if you add it to your cron job (server) it checks the Apache and restart it if it not running and if you want you can add the mail notification option to have an email about it.

*/10 * * * * root /bin/bash /etc/scripts/apache_check.sh >> /etc/logs/apache_check.log 2>&1 #check apache

Above Cronjob Command Runs the script which is located in var/www/scripts/apache_check.sh every 10 minutes and save the result in apache_check.log in /etc/logs folder.

Posted in: Developers, Methodologies, source code Tagged: apache, shell, shell script

Blog Posts

  • How to Design and Implement Software Architecture Patterns: 5 Best Practices
  • Unveiling the Top Traits of a Successful Software Engineer – What it takes to Excel in the Competitive World of Tech
  • Decoding Software Architecture: Your Guide to the Design Process
  • How to improve your soft skills as a software developer?
  • 12 Soft Skills That Every Developer Must Learn to Succeed

Copyright © 2025 Naser Sobhan.

Me WordPress Theme by themehall.com