前言
记得刚玩 VPS 的时候,一个 128M 的机器我都能按照一个 LANMP 出来跑 WordPress。而现在 64/128M 普遍用于搭建一些网络服务。
因为小内存机器往往比较便宜,可能年付就是 $5 样子,所以厂家都会限制 CPU 和 磁盘IO ,如果超过了就会被 suspend,这是随随便便的事情蛤,而且有些主机商对于 suspend 都是不给予退款的。
所以我们可以借助一些软件来限制 CPU 的使用率和 IO。 还有千万不要用跑分软件跑分,不然准玩完。
安装
cpulimit 就是一款可以对 CPU 使用率进行控制的软件。
包安装
Centos:
yum install cpulimit
Debian/Ubuntu
apt-get install cpulimit
编译安装
cd /tmp
wget 'http://downloads.sourceforge.net/cpulimit/cpulimit-1.1.tar.gz'
tar cpulimit-1.1.tar.gz
cd cpulimit-1.1
make
cp cpulimit /usr/local/sbin/
rm -rf cpulimit*
使用
说明
cpulimit -h
Usage: cpulimit [OPTIONS...] TARGET
OPTIONS
-l, --limit=N percentage of cpu allowed from 0 to 100 (required)//cpu限制的百分比
-v, --verbose show control statistics//显示版本号
-z, --lazy exit if there is no target process, or if it dies//如果限制的进程不存在了,则退出。
-i, --include-children limit also the children processes//包括子进程。
-h, --help display this help and exit //帮助,显示参数
TARGET must be exactly one of these:
-p, --pid=N pid of the process (implies -z) //进程的pid
-e, --exe=FILE name of the executable program file or path name //可执行程序
COMMAND [ARGS] run this command and limit it (implies -z)
用法
限制firefox使用30% cpu 利用率
cpulimit -e firefox -l 30
限制进程号1313的程序使用30% cpu 利用率
cpulimit -p 1313 -l 30
限制绝对路径下该软件的 cpu 利用率
cpulimit -e /usr/local/nginx/sbin/nginx -l 50
注意事项
- -l后面限制的cpu使用量,要根据实际的核心数量而成倍减少。40%的限制生效在1核服务器中,如果是双核服务器,则应该限制到20%,四核服务器限制到10%以此类推。
- root用户可以限制所有的进程,普通用户只能限制自己有权限管理的进程。
限制所有进程的 CPU 使用率
默认情况下 cpulimit 只能对已经存在的进程进行限制,但是设置此脚本为随机自启动即可(设置方法参看上面的脚本链接中),它会对所有进程(包括新建进程)进行监控并限制(3秒检测一次,CPU限制为75%)
这就可以防止因为 CPU 使用率过高而被 suspend 了!
#!/bin/bash while true ; do id=`ps -ef | grep cpulimit | grep -v "grep" | awk '{print $10}' | tail -1` nid=`ps aux | awk '{ if ( $3 > 75 ) print $2 }' | head -1` if [ "${nid}" != "" ] && [ "${nid}" != "${id}" ] ; then cpulimit -p ${nid} -l 75 & echo "[`date`] CpuLimiter run for ${nid} `ps -ef | grep ${nid} | awk '{print $8}' | head -1`" >> /root/cpulimit-log.log fi sleep 3 done
保存到 /root/cpulimit.sh
,会自动生成日志文件 /root/cpulimit-log.log
然后将此降本添加开机启动。
设置为开机启动
修改 /etc/rc.local
在对应位置加入 /root/cpulimit.sh
再重启系统,就会全程限制各个进程的 CPU 使用了!