温馨提示×

centos如何限制进程资源

小樊
35
2026-10-06 03:50:29
栏目: 智能运维

在 CentOS(以及一般 Linux 系统)中,限制进程资源有多种方式,常见且实用的如下:


一、使用 ulimit(用户级限制,最常用)

1. 临时限制(当前 shell 生效)

ulimit -u 100        # 最大进程数
ulimit -n 1024       # 最大打开文件数
ulimit -v 500000     # 最大虚拟内存(KB)
ulimit -t 60         # CPU 时间(秒)
ulimit -f 100000     # 最大文件大小(KB)

查看当前限制:

ulimit -a

2. 永久限制(对用户/服务生效)

编辑:

/etc/security/limits.conf

示例(限制 user1):

user1 soft nproc 100
user1 hard nproc 200
user1 soft nofile 1024
user1 hard nofile 2048

需要 pam_limits.so 支持(默认启用)


二、使用 systemd 限制服务资源(推荐用于服务)

CentOS 7+ 使用 systemd

示例:限制 nginx 服务

systemctl edit nginx

写入:

[Service]
MemoryLimit=512M
CPUQuota=50%
TasksMax=100

重载并重启:

systemctl daemon-reload
systemctl restart nginx

常用参数:

  • MemoryLimit
  • CPUQuota
  • TasksMax
  • IOWeight

三、使用 cgroups(精细控制,适合多进程)

1. 使用 cgconfig(传统方式)

安装:

yum install libcgroup libcgroup-tools

配置 /etc/cgconfig.conf:

group mygroup {
    cpu {
        cpu.cfs_quota_us = 50000;
        cpu.cfs_period_us = 100000;
    }
    memory {
        memory.limit_in_bytes = 512M;
    }
}

启动:

systemctl start cgconfig

将进程加入 cgroup:

cgclassify -g cpu,memory:mygroup <pid>

四、使用 nice / renice(CPU 优先级)

nice -n 10 ./app
renice -n 5 -p 1234

值范围:-20(最高)到 19(最低)


五、使用 cpulimit(限制 CPU 使用率)

yum install cpulimit
cpulimit -p 1234 -l 30

限制进程 CPU 不超过 30%


六、总结建议

场景 推荐方式
限制用户 ulimit
系统服务 systemd
多进程/容器 cgroups
临时降权 nice / cpulimit

如果你能说明 限制什么资源(CPU / 内存 / 进程数) 和 使用场景(用户、服务、脚本),我可以给你更精确的配置示例。

0 踩