Naser Sobhan

Software Development Consultant

  • Home
  • How can I help?
  • Projects
  • About Me
  • Contact me

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

  • 10 Mistakes that Hinder Work Productivity & How to Avoid Them?
  • 20 Essential Software Development Terms You Should Know
  • Developers Salaries: How Much Should You Pay?
  • New Software Development Trends in 2023
  • Who is a 10x Developer And What Does it Take to Be One?

Copyright © 2023 Naser Sobhan.

Me WordPress Theme by themehall.com