Linux Administrator

How to Restart Apache When Low on Memory

High traffic and hungry query can consume all your server memory. In this case Apache will go on hunt for swap space and your site became slow.

In this article I will provide you a very mall script (after all, you are short on memory) that every once in a while will check the amount of free memory remaining and, if necessary, it will restart both the Apache and MySQL.

Hopefully, this would free up some RAM and your server will be good to go for a few more days. And so here is the script, which you can easily adapt to your specific unixoid OS.

Restart Apache When Low on Memory

#!/bin/bash
 
threshold=90 #percent
total=$(free | grep "Mem:" | awk '{print $2}')
remaining=$(free | grep "Mem:" | awk '{print $4}')
current=$(echo "scale=0;100-$remaining * 100 / $total" | bc -l)
 
if [ $current -gt $threshold ]
then
      /etc/init.d/apache2 stop
      /etc/init.d/mysql restart
      /etc/init.d/apache2 start
 
      echo "Restarted apache and mysql on `date +'%Y-%m-%d %H:%M:%S'`. RAM utilization at {current}%" 
      >> /var/log/apache_mysql_restarter.log
fi

Setup this script in the cron to run every couple hours (not too often). Use the log to see how severe is the memory problem. You may want to add the log to rotation to make sure it doesn’t grow too big.

Thank you! for visiting LookLinux.

If you find this tutorial helpful please share with your friends to keep it alive. For more helpful topic browse my website www.looklinux.com. To become an author at LookLinux Submit Article. Stay connected to Facebook.

About the author

mm

Santosh Prasad

Hi! I'm Santosh and I'm here to post some cool article for you. If you have any query and suggestion please comment in comment section.

Leave a Comment