Back to Insights
DevelopersJun 25, 20191 min read

Simple Bash Script to Restart Apache when it fails

Naser Sobhan

Naser Sobhan

AI & Strategy Consultant

Cover for the article: Simple Bash Script to Restart Apache when it fails

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.

Naser Sobhan

Written by

Naser Sobhan

A technology veteran with 18+ years building scalable systems for global enterprises. Now based in Rochester, MN, helping local businesses adopt AI safely and profitably.

How this is written: I'm a builder first, not a professional writer — my strength is the technical work, not turning it into prose. The ideas, opinions, and experience here are entirely mine, shaped by years actually doing this. I use AI to help organize my notes, tighten the language, and turn what's in my head into something worth reading.

Keep reading

All insights →