温馨提示×

debian ulimit不生效咋办

小樊
44
2026-09-07 01:30:19
栏目: 智能运维

在 Debian 里 ulimit “不生效”是非常常见的问题,通常不是命令本身的问题,而是作用范围/配置位置不对。下面按「最常见原因 → 解决办法」给你一套排查清单。


一、先明确一个核心点(最重要)

ulimit 只对“当前 shell 及其子进程”有效

下面这些都不会生效

  • 只对当前终端生效
  • 退出 shell 后失效
  • 对已经运行的进程无效
  • 对 systemd 服务默认无效(重点)

二、最常见 6 种“不生效”场景 & 解决

1️⃣ 只在当前 shell 设了,重启/新终端就没了

ulimit -n 65535

✅ 解决:写进 shell 配置(仅交互 shell)

# 对当前用户
echo "ulimit -n 65535" >> ~/.bashrc

⚠️ 注意:

  • 非登录 shell / cron / systemd 不生效

2️⃣ 写在 /etc/profile 但 systemd 服务不读

这是 90% 的人踩坑点

/etc/profile
/etc/bash.bashrc

❌ 对 systemd 启动的服务(nginx / mysql / redis)完全无效

✅ 正确方式(见第 5 点)


3️⃣ /etc/security/limits.conf 没生效

你做了:

* soft nofile 65535
* hard nofile 65535

但还是不生效?

✅ 必须满足 3 个条件

① 使用 PAM

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

没有就加:

session required pam_limits.so

② 只对「登录用户」生效

  • SSH 登录 ✅
  • su - user ✅
  • 直接 systemd ❌

③ 重启或重新登录

logout

验证:

ulimit -n

4️⃣ systemd 服务不读 limits.conf(重点)

比如:

systemctl restart nginx

必须改 service 文件

systemctl edit nginx

写入:

[Service]
LimitNOFILE=65535
LimitNPROC=65535

然后:

systemctl daemon-reload
systemctl restart nginx

验证:

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

5️⃣ 全局 systemd 限制(坑中坑)

即使你改了 service,也可能被系统限制。

查看:

systemctl show --property=DefaultLimitNOFILE

修改:

/etc/systemd/system.conf
DefaultLimitNOFILE=65535
DefaultLimitNPROC=65535

然后:

systemctl daemon-reexec

6️⃣ Docker / 容器里不生效

Docker 默认继承宿主,但可覆盖

docker run --ulimit nofile=65535:65535 ...

或 compose:

ulimits:
  nofile:
    soft: 65535
    hard: 65535

三、快速自检清单 ✅

# 当前 shell
ulimit -a

# 某个进程
cat /proc/<pid>/limits

# systemd 服务
systemctl show <service> | grep Limit

四、一句话总结

场景 正确方式
当前用户 ~/.bashrc
登录用户 /etc/security/limits.conf
systemd 服务 systemctl edit
全局 systemd/system.conf
Docker --ulimit

如果你愿意,可以告诉我:

  • Debian 版本
  • 想限制什么(nofile / nproc / 内存)
  • 是「用户」还是「某个服务」不生效

我可以直接给你可复制的配置

0