在 Debian 中修改 ulimit(资源限制)有多种方式,取决于你是临时生效还是永久生效,以及是对当前 shell、某用户还是系统级生效。
下面按常见场景说明。
直接在终端执行:
ulimit -n 65535 # 打开文件数
ulimit -u 4096 # 最大进程数
ulimit -s 8192 # 栈大小(KB)
查看当前限制:
ulimit -a
⚠️ 只对当前 shell 及其子进程生效,重启或新开 shell 失效。
/etc/security/limits.conf编辑文件:
sudo vim /etc/security/limits.conf
示例(对 www-data 用户):
www-data soft nofile 65535
www-data hard nofile 65535
www-data soft nproc 4096
www-data hard nproc 4096
说明:
soft:软限制(可临时超过)hard:硬限制(不能超过)nofile:打开文件数nproc:进程数⚠️ 需要 PAM 支持(见下一步)
检查以下文件中是否有:
grep pam_limits /etc/pam.d/common-session
grep pam_limits /etc/pam.d/common-session-noninteractive
如果没有,添加:
session required pam_limits.so
su - www-data
ulimit -a
如果你是 Debian 8+,很多服务由 systemd 管理,
limits.conf 不会自动生效!
sudo systemctl edit nginx
写入:
[Service]
LimitNOFILE=65535
LimitNPROC=4096
然后:
sudo systemctl daemon-reload
sudo systemctl restart nginx
查看是否生效:
cat /proc/$(pgrep nginx | head -1)/limits
编辑:
sudo vim /etc/systemd/system.conf
修改:
DefaultLimitNOFILE=65535
DefaultLimitNPROC=4096
然后:
sudo systemctl daemon-reexec
有些限制还受内核影响:
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
| 问题 | 原因 |
|---|---|
| limits.conf 不生效 | systemd 服务未配置 |
| 修改后没变化 | 没重新登录 / 重启服务 |
| root 不生效 | root 默认不受部分限制 |
| Docker 容器 | 需在宿主机或 docker run 指定 |
如果你能说明:
我可以给你更精确的配置示例。