在 CentOS(以及大多数 Linux 发行版)中,ulimit “失效”是一个非常常见的问题,通常不是 ulimit 本身坏了,而是作用范围、配置位置或系统限制导致了“看起来没生效”。
下面按最常见原因 → 排查方法 → 正确配置方式来说明。
ulimit -n 65535
./my_server
✅ 生效
但如果是:
systemctl start my_server
❌ 不生效
原因:
systemctl 启动的进程 不继承你 shell 的 ulimit✅ 正确方式(见后面 systemd 部分)
文件:
/etc/security/limits.conf
示例:
* soft nofile 65535
* hard nofile 65535
❌ 对以下情况不生效:
✅ 生效条件:
pam_limits.so检查 PAM:
grep pam_limits /etc/pam.d/login
grep pam_limits /etc/pam.d/sshd
即使你设置了:
/etc/security/limits.conf
systemctl 启动的服务 完全不看它
✅ 必须改 service 文件:
/etc/systemd/system/xxx.service
[Service]
LimitNOFILE=65535
LimitNPROC=65535
然后:
systemctl daemon-reexec
systemctl restart xxx
查看是否生效:
cat /proc/<pid>/limits
* 不包含 root* soft nofile 65535
❌ root 不生效
✅ 必须单独写:
root soft nofile 65535
root hard nofile 65535
即使 ulimit 设了,内核也可能拦你:
sysctl fs.file-max
如果太小:
fs.file-max = 1000000
生效:
sysctl -p
limits.conf 通常无效docker run --ulimit nofile=65535:65535 ...
你可以一步步确认:
# 当前 shell
ulimit -n
# 进程实际限制
cat /proc/<pid>/limits
# systemd 服务
systemctl show xxx | grep Limit
# 内核
sysctl fs.file-max
/etc/security/limits.conf
/etc/systemd/system/xxx.service
LimitNOFILE=65535
fs.file-max
如果你愿意,可以告诉我:
我可以直接给你精确配置示例。