restart Apache automatically when high load

Question: How to set Cron to restart Apache automatically ?
Ans: You can add the following cron to restart  Apache automatically when it was down for any reason or if the server load is 20.

vi /var/spool/cron/root

*/2 * * * * /bin/sh /root/apache-load-checker.sh > /dev/null 2>&1


#!/bin/bash

#You can set the Load limit as per your requirement
HIGHLIMIT=20
LOWLIMIT=5

#########################################################
#NO NEED TO EDIT ANYTHING BELOW HERE
#########################################################
loadavg=`uptime | awk ‘{print $9}’`
if [ “$loadavg” = “average:” ]
then
echo “not this one…”
loadavg=`uptime | awk ‘{print $10}’`
fi
#RESTARTCOMMAND=”/sbin/service httpd restart”
#STOPCOMMAND=”/sbin/service httpd stop”
RESTARTCOMMAND=”/scripts/restartsrv_httpd”
STOPCOMMAND=”/sbin/service httpd stop”
# bash doesn’t understand floating point
# so convert the number to an interger
thisloadavg=`echo $loadavg|awk -F \. ‘{print $1}’`
if [ “$thisloadavg” -ge “$HIGHLIMIT” ]; then
echo “Busy – Load Average $loadavg ($thisloadavg) ”
#stop apache
$STOPCOMMAND
elif [ “$thisloadavg” -le “$LOWLIMIT” ]; then
echo “Okay – Load Average $loadavg ($thisloadavg) ”
pgrep httpd
if [ $? -ne 0 ] # if apache not running
then
# restart apache
$RESTARTCOMMAND
echo “restart!”
else
echo “no restart!”
fi
else
echo “waiting…!”
fi


 

Leave a Comment