温馨提示×

为什么改了debian ulimit无效

小樊
50
2026-10-24 13:16:03
栏目: 智能运维

在 Debian(以及大多数 Linux 发行版)里,改了 ulimit 却不生效,通常不是“命令写错了”,而是改错地方 / 改的层级不对。下面按最常见原因给你梳理。


一、最常见原因:ulimit 只对“当前 shell 及其子进程”有效

ulimit 是 shell 内建命令,不是系统全局配置。

ulimit -n 65535

✅ 只在:

  • 当前 shell
  • 当前 shell 启动的进程

中有效。

❌ 对以下情况完全无效:

  • 已经运行的进程
  • 系统服务(systemd 服务)
  • 重新登录后的新 shell(除非写进配置文件)

二、你可能在「错误的地方」改了

❌ 只在终端里执行

ulimit -n 100000

退出终端再连,失效。


✅ 想对“登录用户”永久生效

写进用户 shell 配置(注意 shell 类型):

bash 用户

# ~/.bashrc 或 ~/.profile
ulimit -n 65535

登录 shell 才生效

# ~/.bash_profile
ulimit -n 65535

⚠️ 注意:

  • SSH 登录 ≠ 一定读 .bashrc
  • 非交互 shell 可能不读

三、Debian 真正“限制用户”的地方:limits.conf

正确位置

/etc/security/limits.conf

示例:

* soft nofile 65535
* hard nofile 65535

或针对用户:

www-data soft nofile 65535
www-data hard nofile 65535

⚠️ 关键点(很多人栽这里)

  1. 必须重新登录
  2. PAM 要启用
    /etc/pam.d/common-session
    /etc/pam.d/common-session-noninteractive
    
    需要有:
    session required pam_limits.so
    

四、systemd 服务:limits.conf 完全没用!

这是 Debian 10+ 最常见“改了无效”的原因。

systemd 服务不受 ulimit / limits.conf 影响

比如 nginx / mysql / java 服务:

systemctl restart nginx

✅ 正确做法:改 service 文件

# /etc/systemd/system/nginx.service.d/limits.conf
[Service]
LimitNOFILE=65535

然后:

systemctl daemon-reload
systemctl restart nginx

查看是否生效:

cat /proc/<pid>/limits

五、Docker / 容器里改了也无效?

容器里:

  • ulimit 来自 宿主机
  • Docker 启动时限制
docker run --ulimit nofile=65535:65535 ...

或 docker-compose:

ulimits:
  nofile:
    soft: 65535
    hard: 65535

六、内核参数没开(极少但可能)

sysctl fs.file-max

太小就改:

# /etc/sysctl.conf
fs.file-max = 1000000
sysctl -p

七、快速自查清单 ✅

场景 正确方式
当前 shell ulimit
登录用户 limits.conf
systemd 服务 service.d/*.conf
Docker --ulimit
已运行进程 无法改,只能重启

八、你可以告诉我这 3 点,我能精准定位

  1. 你改的是 哪个文件 / 哪条命令
  2. 是 用户进程 还是 系统服务
  3. Debian 版本 + 是否用 systemd

我可以直接告诉你“哪里错了,怎么改一行生效”。

0 踩