Linux VPS通过安装CPULimit来限制CPU使用率

97次阅读
没有评论

共计 1925 个字符,预计需要花费 5 分钟才能阅读完成。

 说明:我们手上经常有很多廉价的VPS,有时候使用某些软件应用的时候,会出现CPU跑满的情况,而长时间跑满会被VPS商家停掉,所以这里我们需要想办法来限制进程CPU使用率,这里就说个教程。

简介

cpulimit命令的工作原理是为进程预设一个cpu占用率上限,并实时监控进程是否超出此上限,而做出动态调整。从而可以控制进程的cpu使用率的上限值。

安装

使用root运行命令:

#debian/ubuntu系统
apt install -y cpulimit

#RHEL/Centos/Fedora系统
yum install epel-release 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)

用法

1、常规用法

#限制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

2、限制所有进程的CPU使用率
默认情况下cpulimit只能对已经存在的进程进行限制,但是设置此脚本为随机自启动即可,它会对所有进程(包括新建进程)进行监控并限制(3秒检测一次,CPU限制为75%)

这就可以防止因为CPU使用率过高而被ban了!

#!/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使用了!

注意事项

l、后面限制的cpu使用量,要根据实际的核心数量而成倍减少。40%的限制生效在1核服务器中,如果是双核服务器,则应该限制到20%,四核服务器限制到10%以此类推。
2、root用户可以限制所有的进程,普通用户只能限制自己有权限管理的进程。
正文完
 
admin
版权声明:本站原创文章,由 admin 2019-09-18发表,共计1925字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码