温馨提示×

debian ulimit怎样修改

小樊
44
2026-09-12 20:32:55
栏目: 智能运维

在 Debian 中修改 ulimit(资源限制)有多种方式,取决于你是临时生效还是永久生效,以及是对当前 shell某用户还是系统级生效。

下面按常见场景说明。


一、临时修改(当前 shell 会话)

直接在终端执行:

ulimit -n 65535      # 打开文件数
ulimit -u 4096       # 最大进程数
ulimit -s 8192       # 栈大小(KB)

查看当前限制:

ulimit -a

⚠️ 只对当前 shell 及其子进程生效,重启或新开 shell 失效。


二、对用户永久生效(推荐方式)

1️⃣ 使用 /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 支持(见下一步)


2️⃣ 确保 PAM 启用 limits

检查以下文件中是否有:

grep pam_limits /etc/pam.d/common-session
grep pam_limits /etc/pam.d/common-session-noninteractive

如果没有,添加:

session required pam_limits.so

3️⃣ 重新登录用户生效

su - www-data
ulimit -a

三、对 systemd 服务生效(非常重要)

如果你是 Debian 8+,很多服务由 systemd 管理,
limits.conf 不会自动生效

方法 1:修改 service 文件

sudo systemctl edit nginx

写入:

[Service]
LimitNOFILE=65535
LimitNPROC=4096

然后:

sudo systemctl daemon-reload
sudo systemctl restart nginx

查看是否生效:

cat /proc/$(pgrep nginx | head -1)/limits

方法 2:全局 systemd 限制

编辑:

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 指定

如果你能说明:

  • Debian 版本
  • 修改的是哪种限制(nofile / nproc / 内存)
  • 是给用户还是服务

我可以给你更精确的配置示例。

0