Ubuntu – Kill off apache processes when memory usage hits 90%

Apache2server

My situation is following: We run Magento Professional on a 15Gb ram instance, rackspace.

When running htop, we could see that 'apache2 -k start' keeps spawning more child processes, some of them eats ~900Mb of memory.

When memory is almost used up, all sites time out or become very slow. When memory is all used up, it seems that some of these processes got killed to free memory.

Then the same procedures happen.

My question is, could we setup ubuntu / apache to kill off child processes and free memory when memory usage reaches 85-90% ?

Best Answer

#!/bin/sh
TOTAL=`cat /proc/meminfo | grep MemTotal: | awk '{print $2}'`
USEDMEM=`cat /proc/meminfo | grep Active: | awk '{print $2}'`
LOG=/var/log/apache-free.log
LIMIT=90
DATA=`date +%Y-%m-%d" "%H:%M:%S`

if [ "$USEDMEM" -gt 0 ]
 then
    USEDMEMPER=$(($USEDMEM * 100 / $TOTAL))
    USEDMEMPERLOG=$USEDMEMPER
    if [ $USEDMEMPER -lt $LIMIT ]; then
                echo "$DATA | Memory: $USEDMEMPER%, (limit: $LIMIT%) | Do not restart!"
    else
                echo "$DATA | Memory limit reached ($LIMIT%): $USEDMEMPERLOG% | Restarting apache..."
                # restart apache
                sudo service apache2 restart
                TOTAL=`cat /proc/meminfo | grep MemTotal: | awk '{print $2}'`
                USEDMEM=`cat /proc/meminfo | grep Active: | awk '{print $2}'`
                USEDMEMPER=$(($USEDMEM * 100 / $TOTAL))
                echo "$DATA | Memory limit reached ($LIMIT%): $USEDMEMPERLOG% | Memory after restart: $USEDMEMPER%" >> $LOG
                tail -1 $LOG
    fi
fi

Save this code as apache-free.sh file and set as executable and add permissions

chmod +X apache-free.sh
chmod 755 apache-free.sh

add a crontab schedule, to run every 1 minute (feel free to redefine this time)

crontab -e

*/1 * * * * cd /dir/of/script && sh apache-free.sh

This script saves a log file in /var/log/apache-free.log with some informations about execution and memory saves.

** Remember: It's only a bandaid! It's necessary detect the real problem with your server.

I hope helps you!

Related Question