温馨提示×

为什么ubuntu ulimit受限

小樊
57
2026-10-17 07:14:40
栏目: 智能运维

在 Ubuntu(以及绝大多数 Linux 发行版)里,ulimit 受限是“设计如此”,而不是 bug。背后主要有几类原因:系统安全、资源隔离、默认策略、以及 systemd 的干预。下面分层说明。


一、ulimit 是什么(先澄清概念)

ulimit 是 shell 内建命令,用来限制当前 shell 及其子进程能使用的资源:

  • 打开文件数(nofile)
  • 进程/线程数(nproc)
  • 栈大小(stack)
  • 内存(memory)
  • core 文件大小
  • CPU 时间等

⚠️ 注意:

ulimit 只能“调小”,不能突破系统硬限制


二、为什么你会感觉“受限”

1️⃣ 系统有默认值(hard limit)

Ubuntu 默认:

  • nofile 软限制:1024
  • nofile 硬限制:1048576(或更高)
  • nproc:通常和用户名相关

很多服务(数据库、Web、消息队列)很容易超过 1024 文件描述符。


2️⃣ PAM + limits.conf(只对“登录用户”生效)

Ubuntu 通过 PAM 限制用户资源:

/etc/security/limits.conf

示例:

* soft nofile 1024
* hard nofile 1048576

⚠️ 但:

  • 只对 login shell
  • 对 systemd 启动的服务无效

3️⃣ systemd 会“覆盖”ulimit(这是最常见坑)

如果你用:

systemctl start nginx

那它 根本不看 ulimit / limits.conf

而是看:

/etc/systemd/system.conf
/etc/systemd/user.conf

或服务单元文件:

[Service]
LimitNOFILE=65535
LimitNPROC=65535

✅ 所以:

你在 shell 里 ulimit -n 65535,对 systemd 服务没用


4️⃣ 容器 / WSL / 云服务器额外限制

  • Docker:默认限制
  • Kubernetes:有 cgroup 限制
  • WSL:某些版本 ulimit 是假的
  • 云厂商:内核参数被锁

5️⃣ 非 root 用户不能提高 hard limit

ulimit -Hn   # 硬限制
ulimit -Sn   # 软限制

普通用户:

  • 只能降低
  • 不能提高 hard limit

只有 root 可以。


三、正确的“解锁”方式(按场景)

✅ 场景 1:登录用户(SSH)

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

并确认:

/etc/pam.d/common-session

包含:

session required pam_limits.so

✅ 场景 2:systemd 服务(推荐)

# /etc/systemd/system/xxx.service
[Service]
LimitNOFILE=100000
LimitNPROC=100000

然后:

systemctl daemon-reexec
systemctl restart xxx

✅ 场景 3:临时测试

ulimit -n 65535

只对当前 shell 和子进程有效。


四、为什么 Ubuntu 要“默认限制”?

核心原因只有一个词:**稳定性 & 安全

  • 防止fork bomb
  • 防止 fd 泄漏拖垮系统
  • 多用户公平分配资源
  • 避免新手把系统搞崩

五、一句话总结

Ubuntu 的 ulimit 受限,是因为 Linux 从内核到 systemd 都在“按规则管资源”,而很多人误以为 shell 的 ulimit 能管所有进程。

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

  • 你是 普通用户 / root
  • 是 shell / systemd / Docker / WSL
  • 具体卡在哪种限制(nofile / nproc / 内存)

我可以直接给你可用配置。

0 踩