温馨提示×

为何debian ulimit失效

小樊
46
2026-09-19 02:59:15
栏目: 智能运维

在 Debian 上遇到 ulimit 不生效 / 失效,通常不是“系统 bug”,而是作用范围或配置位置不对。下面按最常见原因系统说明。


一、ulimit 的本质(先弄清这一点)

ulimitshell 内建命令,作用是:

修改当前 shell 及其子进程的资源限制

❌ 它不能影响:

  • 已经启动的进程
  • 其他登录会话
  • systemd 管理的服务(默认)

✅ 它只能

  • 影响当前 shell
  • 当前 shell 启动的子进程

二、最常见的“失效”原因

1️⃣ 在 systemd 服务里用 ulimit(完全无效)

例如:

[Service]
ExecStart=/usr/bin/myapp

你在终端执行:

ulimit -n 65535

服务根本不受影响

✅ 正确方式(systemd):

[Service]
LimitNOFILE=65535

然后:

systemctl daemon-reload
systemctl restart myapp

2️⃣ 修改了 /etc/profile,但进程不是从 shell 启动

例如:

  • Docker 容器
  • cron
  • systemd
  • 某些守护进程

这些不读取 /etc/profile

✅ 解决:

  • Docker:--ulimit
  • cron:在脚本里设
  • systemd:用 Limit*

3️⃣ /etc/security/limits.conf 没生效(PAM 问题)

常见于:

  • SSH 登录不生效
  • su 不生效

原因:

limits.conf 依赖 PAM

检查:

grep pam_limits /etc/pam.d/login
grep pam_limits /etc/pam.d/sshd

必须有:

session required pam_limits.so

否则 limits.conf 完全无效。


4️⃣ 修改了 limits.conf,但用的是 root 启动进程

⚠️ 重点:

limits.confroot 用户不生效(除非显式指定)

错误示例:

* soft nofile 65535

✅ 正确:

root soft nofile 65535
root hard nofile 65535

5️⃣ hard limit 限制了 soft limit

例如:

ulimit -Hn
1024

你执行:

ulimit -Sn 65535

❌ 会被拒绝

✅ 必须先提高 hard limit(root):

ulimit -Hn 65535

6️⃣ Debian 默认 nofile 已是高值(你以为没生效)

Debian 11/12:

  • 普通用户:1024
  • root:1048576

你设 65535,但:

  • 服务用的是 systemd
  • 实际已是 1M

用以下命令确认:

cat /proc/<pid>/limits

三、正确的“通用配置方案”

✅ 用户登录会话

/etc/security/limits.conf
  • 确保 PAM 启用

✅ systemd 服务

LimitNOFILE=65535
LimitNPROC=65535

✅ Docker

docker run --ulimit nofile=65535:65535

✅ 临时测试

ulimit -n 65535
./your_program

四、快速自检清单

# 当前 shell
ulimit -a

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

# PAM
grep pam_limits /etc/pam.d/*

# systemd
systemctl show xxx | grep Limit

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

  • Debian 版本
  • 你是 登录用户 / 服务 / Docker / cron
  • 想改的是 nofile / nproc / stack / core

我可以直接给你精确可用的配置

0