在 Ubuntu(以及绝大多数 Linux 发行版)里,ulimit 受限是“设计如此”,而不是 bug。背后主要有几类原因:系统安全、资源隔离、默认策略、以及 systemd 的干预。下面分层说明。
ulimit 是 shell 内建命令,用来限制当前 shell 及其子进程能使用的资源:
⚠️ 注意:
ulimit 只能“调小”,不能突破系统硬限制
Ubuntu 默认:
nofile 软限制:1024nofile 硬限制:1048576(或更高)nproc:通常和用户名相关很多服务(数据库、Web、消息队列)很容易超过 1024 文件描述符。
Ubuntu 通过 PAM 限制用户资源:
/etc/security/limits.conf
示例:
* soft nofile 1024
* hard nofile 1048576
⚠️ 但:
如果你用:
systemctl start nginx
那它 根本不看 ulimit / limits.conf
而是看:
/etc/systemd/system.conf
/etc/systemd/user.conf
或服务单元文件:
[Service]
LimitNOFILE=65535
LimitNPROC=65535
✅ 所以:
你在 shell 里
ulimit -n 65535,对 systemd 服务没用
ulimit -Hn # 硬限制
ulimit -Sn # 软限制
普通用户:
只有 root 可以。
# /etc/security/limits.conf
youruser soft nofile 65535
youruser hard nofile 65535
并确认:
/etc/pam.d/common-session
包含:
session required pam_limits.so
# /etc/systemd/system/xxx.service
[Service]
LimitNOFILE=100000
LimitNPROC=100000
然后:
systemctl daemon-reexec
systemctl restart xxx
ulimit -n 65535
只对当前 shell 和子进程有效。
核心原因只有一个词:**稳定性 & 安全
Ubuntu 的 ulimit 受限,是因为 Linux 从内核到 systemd 都在“按规则管资源”,而很多人误以为 shell 的 ulimit 能管所有进程。
如果你愿意,可以告诉我:
我可以直接给你可用配置。