linux服务器内存、负载过高自动重启apache脚本

linux服务器内存、负载过高自动重启apache脚本

由于好玩吧的centos服务器用的是阿里云的服务器,内存只有1G,最近升级了2G,感觉还是操作起来还是很卡,wordpress又巨吃内存。无奈为了避免内存溢出服务器挂掉,采取shell脚本来执行

代码如下:

#mkdir -p /data/software/restart_apache/

#vi /data/software/restart_apache/loadavg_restart_apache.sh

以下内容:

#!/bin/sh

# crontab: */3 * * * * /data/software/restart_apache/loadavg_restart_apache.sh >> /data/software/restart_apache/restart_apache.log

#TOP_SYS_LOAD_NUM表示到达这个负载的时候,就会停止apache。然后过段时间负载降下来后,再尝试启动apache(单核建议1,双核2)
TOP_SYS_LOAD_NUM=1	
SYS_LOAD_NUM=`uptime | awk '{print $(NF-2)}' | sed 's/,//'`  

#MIN_RAM表示系统可用内存如果小于此设置的时候(单位MB),就会停止apache。然后过段时间负载降下来后,再尝试启动apache
MIN_RAM=100			
FREE_RAM=`free -m| grep Mem|awk '{print $4}'`

echo $(date +"%y-%m-%d") `uptime`
if [ `echo "$TOP_SYS_LOAD_NUM < $SYS_LOAD_NUM"|bc` -eq 1 ] ||  [ `echo "$FREE_RAM < $MIN_RAM"|bc` -eq 1 ]
then  
    echo "#0#" $(date +"%y-%m-%d %H:%M:%S") "pkill httpd" `ps -ef | grep httpd | wc -l`
    #/usr/sbin/apachectl stop
	/etc/init.d/httpd stop
    sleep 8		#休眠8秒之后
    pkill httpd  
    sleep 8  
    for i in 1 2 3  
    do  
        if [ `pgrep httpd | wc -l` -le 0 ]  
        then  
            #/usr/sbin/apachectl start 
			/etc/init.d/httpd start
            sleep 30  
            echo "#1#" $(date +"%y-%m-%d %H:%M:%S") "start httpd" `ps -ef | grep httpd | wc -l`  
        fi  
    done  
else  
    if [ `pgrep httpd | wc -l` -le 0 ]  
    then  
        #/usr/sbin/apachectl start 
		/etc/init.d/httpd start		
        sleep 30  
        echo "#2#" $(date +"%y-%m-%d %H:%M:%S") "start httpd" `ps -ef | grep httpd | wc -l`  
    fi  
fi 

chmod +x /data/software/restart_apache/loadavg_restart_apache.sh

echo
'*/3 * * * * /data/software/restart_apache/loadavg_restart_apache.sh
>> /data/software/restart_apache/restart_apache.log' >>
/etc/crontab

监控日志文件:

tail -f /data/software/restart_apache/restart_apache.log

如果脚本执行如果报错

/backup/www.cthome.com/loadavg_restart_apache.sh: line 6: bc: command not found
/backup/www.cthome.com/loadavg_restart_apache.sh: line 6: [: -eq: unary operator expected

表示没有bc命令,centos可以用 yum -y install bc 安装它

参考:http://www.ctohome.com/FuWuQi/e0/404.html

未经允许不得转载:好玩吧 » linux服务器内存、负载过高自动重启apache脚本