温馨提示×

重启后debian ulimit为何失效

小樊
48
2026-10-09 21:37:43
栏目: 智能运维

在 Debian(以及大多数 Linux 发行版)上,重启后 ulimit 失效是非常常见的现象,原因通常不是“设置错了”,而是设置的位置或方式不对。下面按「原因 → 解决方案」说明。


一、为什么重启后 ulimit 会失效?

1. ulimit 是「进程级」设置,不是系统级

  • ulimit 只在当前 shell 及其子进程中生效
  • 重启后:
    • 新的登录 shell 不会自动继承你之前手动设置的 ulimit
  • 所以:
    ulimit -n 65535
    
    只是“临时生效”

2. 写在 ~/.bashrc / ~/.profile 可能不生效

  • 很多服务 不是由交互 shell 启动的
  • 例如:
    • systemd 服务
    • docker 容器
    • nginx / mysql 等后台进程
  • 这些进程 根本不会读 .bashrc

3. Debian 使用 systemd(重点)

在 Debian 8+(使用 systemd) 后:

  • ulimit 被 systemd 的 resource limit 接管
  • 传统 /etc/security/limits.conf 只对登录会话有效
  • 对 systemd 服务无效

二、正确的设置方式(按使用场景)


✅ 场景 1:普通用户登录后生效(SSH / 终端)

方法 1:/etc/security/limits.conf

sudo vim /etc/security/limits.conf

示例(对所有用户):

* soft nofile 65535
* hard nofile 65535

⚠ 注意:

  • 需要 PAM 支持
  • 需确保:
    grep pam_limits /etc/pam.d/common-session
    
    有:
    session required pam_limits.so
    

✅ 重启或重新登录后生效


✅ 场景 2:某个 systemd 服务(如 nginx / java / redis)

方法 2:systemd 服务文件

sudo systemctl edit nginx

添加:

[Service]
LimitNOFILE=65535
LimitNPROC=65535

然后:

sudo systemctl daemon-reload
sudo systemctl restart nginx

✅ 重启服务器也生效


✅ 场景 3:全局 systemd 默认限制

sudo vim /etc/systemd/system.conf

修改:

DefaultLimitNOFILE=65535
DefaultLimitNPROC=65535

然后:

sudo systemctl daemon-reexec

✅ 场景 4:Docker 容器

Docker 不会继承宿主机的 ulimit 需要在运行容器时指定:

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

或 docker-compose:

ulimits:
  nofile:
    soft: 65535
    hard: 65535

三、如何验证当前生效值?

# 当前 shell
ulimit -n

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

四、总结一句话

重启后 ulimit 失效,是因为你设在了“临时 shell”,而不是“进程/服务真正读取的地方”。

如果你能告诉我:

  • Debian 版本
  • 是「用户」还是「服务」
  • 具体是 nofile / nproc / 其他

我可以给你完全对应的配置示例。

0 踩