温馨提示×

Debian ulimit为何不生效

小樊
40
2026-07-11 23:48:45
栏目: 智能运维

在 Debian(以及大多数 Linux 发行版)中,ulimit 设置“不生效”通常不是命令本身的问题,而是设置位置、作用范围或 systemd 的限制导致的。下面按常见原因逐一说明,并给出对应的解决办法。


一、ulimit 的基本限制(必须理解)

  1. ulimit 只对当前 shell 及其子进程生效

    ulimit -n 65535
    

    只在当前 shell 会话中有效,退出后失效。

  2. 普通用户不能“调大”超过硬限制

    ulimit -Hn   # 查看硬限制
    ulimit -Sn   # 查看软限制
    
    • 软限制 ≤ 硬限制
    • 非 root 用户不能提高硬限制

二、最常见的 5 个“不生效”原因

1️⃣ 在 /etc/profile / ~/.bashrc 里设置但没用

ulimit -n 65535

原因

  • 仅对交互式 shell生效
  • 对 systemd 启动的服务、cron、docker 完全无效

解决

  • 服务:用 systemd 配置
  • 用户登录:用 /etc/security/limits.conf

2️⃣ 没启用 pam_limits.so

/etc/security/limits.conf 依赖 PAM。

检查

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

如果没有:

session required pam_limits.so

解决

echo "session required pam_limits.so" >> /etc/pam.d/common-session

⚠️ 修改后重新登录才生效(不是 source)


3️⃣ systemd 会忽略 ulimit / limits.conf

这是 Debian 10+ / systemd 系统最常见原因

即使你设置了:

* soft nofile 65535
* hard nofile 65535

systemd 服务仍然不生效

✅ 正确做法(systemd)

编辑服务:

systemctl edit your.service

添加:

[Service]
LimitNOFILE=65535

然后:

systemctl daemon-reexec
systemctl restart your.service

验证:

cat /proc/$(pidof your_service)/limits

4️⃣ Debian 默认 nofile 是 1024 / 1048576

Debian 默认值:

  • 软限制:1024
  • 硬限制:1048576

如果你写:

* hard nofile 100000

但系统最大是 1048576,看起来“没生效”是正常的。

建议

* soft nofile 65535
* hard nofile 65535

5️⃣ Docker / LXC / Kubernetes 场景

ulimit 在容器里由宿主机控制

✅ Docker 示例:

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

❌ 在容器里 ulimit -n 65535 通常无效


三、正确的“全局生效”配置方式(推荐)

✅ 用户登录(SSH)

# /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535

并确认:

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

✅ systemd 服务

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

或 per service:

[Service]
LimitNOFILE=65535

四、快速自检清单 ✅

# 当前 shell
ulimit -n

# 进程
cat /proc/$(pidof xxx)/limits

# systemd
systemctl show your.service | grep Limit

五、一句话总结

ulimit 不生效,99% 是 systemd 或 PAM 的问题,而不是 ulimit 本身。

如果你愿意,可以把你的 使用场景(SSH 用户 / systemd 服务 / Docker / 数据库)贴出来,我可以直接给你一份“可复制可用”的配置。

0