在 Debian(以及大多数 Linux 发行版)中,ulimit 设置重启后失效是正常现象,这是由 ulimit 的设计和 Linux 的进程模型决定的。下面分点说明原因,并给出正确的持久化方法。
ulimit 重启会失效?ulimit 是 进程级 设置ulimit 只影响当前 shell 进程及其子进程ulimit -n 65535
只对你当前 shell 会话有效。
ulimit 不会自动恢复之前的设置ulimit -n 65535
~/.bashrc(不推荐)只对交互式 shell 有效,对服务无效。
/etc/security/limits.conf(最常用)适用于:
sudo vim /etc/security/limits.conf
追加:
* soft nofile 65535
* hard nofile 65535
或指定用户:
www-data soft nofile 65535
www-data hard nofile 65535
检查:
grep pam_limits /etc/pam.d/common-session
如果没有,添加:
session required pam_limits.so
✅ 重启后生效
⚠️ Debian 使用 systemd,limits.conf 对 systemd 服务默认无效
sudo systemctl edit nginx
写入:
[Service]
LimitNOFILE=65535
然后:
sudo systemctl restart nginx
sudo vim /etc/systemd/system.conf
DefaultLimitNOFILE=65535
sudo vim /etc/systemd/user.conf
DefaultLimitNOFILE=65535
然后:
sudo systemctl daemon-reexec
sudo reboot
ulimit -n
cat /proc/$(pidof nginx)/limits | grep "Max open files"
| 误区 | 实际情况 |
|---|---|
| ulimit 是系统级 | ❌ 是进程级 |
| limits.conf 对 systemd 服务有效 | ❌ 默认无效 |
| reboot 后自动保留 | ❌ |
| 写在 bashrc 就够 | ❌ 对服务无效 |
ulimit重启失效是正常行为,必须通过limits.conf或 systemd 配置才能持久化。
如果你愿意,可以告诉我:
我可以给你精确到命令级别的方案。