在 Debian(以及大多数 Linux 发行版)中,很多人会遇到 ulimit 设置后不生效 的问题。通常不是 ulimit 本身无效,而是设置的位置或方式不对。下面按常见原因和正确做法系统说明。
| 原因 | 说明 |
|---|---|
| ❌ 只在当前 shell 设置 | ulimit 只对当前 shell 及其子进程有效 |
| ❌ systemd 忽略 ulimit | 服务由 systemd 启动时,ulimit 不生效 |
❌ 放在 /etc/profile 但没被加载 |
非 login shell 不会读取 |
| ❌ 超过系统硬限制 | 软限制不能高于硬限制 |
❌ 在 /etc/security/limits.conf 中但 PAM 未启用 |
未经过 PAM 的会话不生效 |
ulimit -n 65535
✅ 只影响:
❌ 不影响:
ulimit -Sn # 软限制
ulimit -Hn # 硬限制
如果你看到:
bash: ulimit: open files: cannot modify limit: Operation not permitted
说明你在尝试超过硬限制。
ulimit -n 65535
⚠️ 重启或新 shell 就失效
sudo vim /etc/security/limits.conf
添加:
* soft nofile 65535
* hard nofile 65535
root soft nofile 65535
root hard nofile 65535
Debian 默认是启用的,但确认一下:
grep pam_limits /etc/pam.d/common-session
应该有:
session required pam_limits.so
✅ 适用场景:
❌ 不适用:
sudo systemctl edit your_service
或编辑:
/etc/systemd/system/your_service.service
[Service]
LimitNOFILE=65535
LimitNPROC=65535
systemctl daemon-reload
systemctl restart your_service
✅ 验证:
cat /proc/$(pidof your_service)/limits
sysctl fs.file-max
临时修改:
sudo sysctl -w fs.file-max=1000000
永久:
echo "fs.file-max = 1000000" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
⚠️ 这是 系统能打开的最大 fd 数,不是进程限制。
ulimit -n 还是 1024?✅ 检查顺序:
docker run --ulimit nofile=65535:65535 ...
ulimits:
nofile:
soft: 65535
hard: 65535
| 场景 | 推荐方式 |
|---|---|
| 普通用户登录 | limits.conf |
| systemd 服务 | service 文件 |
| 临时测试 | ulimit |
| 容器 | docker ulimit |
| 系统全局 | sysctl |
Debian 中 ulimit 不生效,90% 是因为 systemd 或设置位置不对。
如果你愿意,可以把你的 具体场景(比如:SSH 登录 / systemd 服务 / Docker / MySQL / Nginx)贴出来,我可以直接给你一套精确可用的配置。