在 Ubuntu 上 ulimit 看起来“失效”,通常不是 ulimit 本身坏了,而是作用范围或设置方式不对。下面按最常见原因逐一说明。
ulimit -n 65535
./my_server
✅ 这样是有效的
❌ 但如果你:
ulimit -n 65535
# 退出 shell
# 重新登录
./my_server
就失效了
ulimit 是 shell 内建命令✅ 正确方式见后面「永久生效方案」
如果你用:
systemctl start myapp
那 ulimit 完全没用
/etc/security/limits.conf 影响(部分情况)在 service 文件里加:
[Service]
LimitNOFILE=65535
LimitNPROC=65535
然后:
systemctl daemon-reload
systemctl restart myapp
你可能在 /etc/security/limits.conf 写了:
* soft nofile 65535
* hard nofile 65535
但还是失效,原因可能是:
检查:
grep pam_limits /etc/pam.d/common-session
应有:
session required pam_limits.so
root soft nofile 65535
❌ 默认 不生效
必须写成:
root soft nofile 65535
root hard nofile 65535
或者直接:
ulimit -n 65535
ulimit -Hn # 硬限制
ulimit -Sn # 软限制
如果你设置:
ulimit -n 100000
但硬限制是 65535,那会失败或自动降级。
Docker 默认限制:
docker run --ulimit nofile=65535:65535 ...
否则:
✅ 正确查看:
cat /proc/<pid>/limits
❌ 错误方式:
ulimit -n # 只是当前 shell
# 1. 当前 shell
ulimit -a
# 2. 某进程
cat /proc/$(pidof xxx)/limits
# 3. systemd 服务
systemctl show xxx | grep Limit
Ubuntu 上 ulimit “失效”,99% 是因为:
- 只在 shell 里设了
- 用 systemd 启动程序
- 没在 service 或容器参数里配置
如果你愿意,可以告诉我:
我可以直接给你可复制的配置。