Linux系统对进程的资源限制主要包括以下几种:
# 查看所有限制
ulimit -a
# 查看特定限制
ulimit -n # 文件描述符数
ulimit -u # 用户进程数
ulimit -v # 虚拟内存大小
# 查看进程限制
cat /proc/<pid>/limits
# 查看系统内存信息
cat /proc/meminfo
# 查看CPU信息
cat /proc/cpuinfo
# 设置文件描述符限制
ulimit -n 65535
# 设置用户进程数限制
ulimit -u 65535
# 设置核心文件大小
ulimit -c unlimited
注意:ulimit设置的修改只在当前会话有效。
# 格式:<domain> <type> <item> <value>
* soft nofile 65535
* hard nofile 65535
root soft nofile 65535
root hard nofile 65535
常见item选项: - nofile - 最大打开文件数 - nproc - 最大进程数 - memlock - 最大锁定内存 - stack - 最大栈大小
对于使用systemd的服务,需要在服务文件中设置:
[Service]
LimitNOFILE=65535
LimitNPROC=65535
然后重新加载并重启服务:
systemctl daemon-reload
systemctl restart <service>
# 创建cgroup
cgcreate -g cpu,memory:/mygroup
# 设置CPU限制
cgset -r cpu.cfs_period_us=100000 mygroup
cgset -r cpu.cfs_quota_us=50000 mygroup # 限制为50% CPU
# 设置内存限制
cgset -r memory.limit_in_bytes=512M mygroup
# 将进程加入cgroup
cgclassify -g cpu,memory:/mygroup <pid>
systemd-run --scope -p CPUQuota=50% -p MemoryLimit=512M command
解决方法:
# 临时提高限制
ulimit -n 65535
# 永久修改
echo "* soft nofile 65535" >> /etc/security/limits.conf
echo "* hard nofile 65535" >> /etc/security/limits.conf
# 对于systemd服务
echo "DefaultLimitNOFILE=65535" >> /etc/systemd/system.conf
systemctl daemon-reload
解决方法:
# 检查OOM killer日志
dmesg | grep oom-killer
# 调整swappiness
sysctl vm.swappiness=10
# 限制特定进程内存使用
cgcreate -g memory:/limited_group
cgset -r memory.limit_in_bytes=1G limited_group
cgclassify -g memory:/limited_group <pid>
解决方法:
# 使用nice调整优先级
nice -n 19 command
# 使用cpulimit工具
cpulimit -l 50 -p <pid> # 限制为50% CPU
# 使用cgroups限制CPU
cgcreate -g cpu:/cpu_limited
cgset -r cpu.cfs_quota_us=50000 cpu_limited # 限制为50% CPU
cgclassify -g cpu:/cpu_limited <pid>
通过合理设置资源限制,可以有效防止单个进程耗尽系统资源,提高系统整体稳定性和安全性。