温馨提示×

centos ulimit怎么设置

小樊
42
2026-10-03 03:06:22
栏目: 智能运维

在 CentOS 中,ulimit 用于限制 用户进程可使用的系统资源(如打开文件数、进程数、内存等)。下面按使用场景给你系统说明。


一、临时设置(当前会话有效)

1. 查看当前限制

ulimit -a

2. 临时修改(仅当前 shell)

ulimit -n 65535        # 打开文件数
ulimit -u 4096         # 最大进程数
ulimit -s 8192        # 栈大小(KB)

⚠️ 重启或重新登录后失效


二、用户级永久设置(推荐)

1. 修改 /etc/security/limits.conf

vi /etc/security/limits.conf

示例(对用户 appuser):

appuser soft nofile 65535
appuser hard nofile 65535
appuser soft nproc 4096
appuser hard nproc 4096

说明:

  • soft:软限制(可临时超过)
  • hard:硬限制(不可超过)
  • nofile:打开文件数
  • nproc:进程数

2. 确保 PAM 生效

检查 /etc/pam.d/login 或 /etc/pam.d/sshd 中是否有:

session required pam_limits.so

一般 CentOS 默认已启用。


3. 重新登录生效

logout

或

su - appuser

三、systemd 服务(重点!)

CentOS 7+ 的 service 不受 limits.conf 影响

修改 service 文件

vi /usr/lib/systemd/system/nginx.service

在 [Service] 下加:

LimitNOFILE=65535
LimitNPROC=4096

然后:

systemctl daemon-reload
systemctl restart nginx

四、系统级全局设置(内核参数)

1. 最大文件句柄数

sysctl -a | grep fs.file-max

修改:

vi /etc/sysctl.conf
fs.file-max = 1000000
sysctl -p

五、常见坑总结

❌ limits.conf 对 root 不生效 ✅ root 需要:

ulimit -n 65535

或使用 systemd

❌ Docker 容器需额外设置

docker run --ulimit nofile=65535:65535

六、快速自查命令

# 当前用户限制
ulimit -n

# 某进程限制
cat /proc/<pid>/limits

如果你告诉我:

  • CentOS 版本(6 / 7 / 8)
  • 是 普通用户 / root / 服务
  • 想调什么(文件数 / 进程数 / 内存)

我可以直接给你精确配置方案。

0 踩