如何调整 worker_rlimit_nofile 突破 65535
解读
国内生产环境常见 Nginx 反向代理或高并发 API 网关,worker_connections 与 worker_rlimit_nofile 直接决定单机可承载的并发连接数。面试官问“突破 65535”并不是单纯让你把数字改成 65536,而是考察候选人是否理解 Linux 的“硬限制-软限制-内核参数-服务重启”完整链路,以及是否具备线上灰度验证、回滚、监控的能力。答不到“系统层面+服务层面+验证闭环”三个维度,基本会被判定为“只背过命令”。
知识点
- 文件描述符上限链路
进程级:RLIMIT_NOFILE(软/硬限制)
系统级:fs.file-max、fs.nr_open
systemd 级:DefaultLimitNOFILE / 单元文件 LimitNOFILE
容器级:docker --ulimit nofile=xxx:xxx - 内核编译常数
__FD_SETSIZE 影响 select,但 epoll 不受其限制;真正天花板是 fs.nr_open(默认 1048576,可写 sysctl 动态改)。 - 用户空间可见性
/proc/sys/fs/nr_open 决定单个进程可设的最大 nofile;/etc/security/limits.conf 只能改到硬限制以下;prlimit 可热修改。 - Nginx 特有行为
worker_rlimit_nofile 在 master 进程启动时通过 setrlimit 生效,无需重启操作系统,但必须 reload 服务;若值高于系统上限,启动报 “setrlimit(RLIMIT_NOFILE, xxx) failed”。 - 国内云厂商差异
阿里云、腾讯云轻量应用服务器默认 fs.nr_open=1048576,但 systemd 的 DefaultLimitNOFILE=65535;华为云 EulerOS 2.0 默认 nr_open 仅 1048576,需手动提升。 - 监控与回滚
需观察 /proc/sys/fs/file-nr、ss -s、nginx error.log “Too many open files”;回滚策略:保留原单元文件,使用 nginx -T 校验配置,通过 consul/nacos 摘除流量后 reload。
答案
线上 CentOS 7/8、Ubuntu 20.04、Alibaba Cloud Linux 3 通用步骤如下,全部在维护窗口内操作,确保有回滚脚本。
-
确认系统级天花板
sysctl fs.nr_open
若小于目标值(如 2000000),写入 /etc/sysctl.d/99-nofile.conf:
fs.nr_open = 2000000
sysctl -p /etc/sysctl.d/99-nofile.conf -
提升全局文件描述符池
echo "fs.file-max = 4194304" >> /etc/sysctl.d/99-nofile.conf
sysctl -p -
调整 systemd 默认限制(防止登录会话被截断)
mkdir -p /etc/systemd/system.conf.d/
cat > /etc/systemd/system.conf.d/nofile.conf <<EOF
[Manager]
DefaultLimitNOFILE=2000000
EOF
systemctl daemon-reexec -
对 Nginx 服务单独设限(推荐做法,不影响其他组件)
systemctl edit nginx
输入:
[Service]
LimitNOFILE=2000000
保存后 systemctl daemon-reload -
修改 nginx.conf
worker_rlimit_nofile 2000000;
worker_processes auto;
events {
worker_connections 400000;
use epoll;
multi_accept on;
}
检查语法:nginx -t -
灰度 reload
nginx -s reload
观察 error.log 无 “setrlimit failed” 字样;
通过 prlimit --pid $(pgrep -f "nginx: worker") --nofile 确认软限制已变为 2000000。 -
压测验证
使用阿里云 PTS 或 wrk2 打 120 万并发连接,监控 ss -s、/proc/sys/fs/file-nr、node_exporter 的 node_filefd_allocated 指标,确保 file-nr 第三列未逼近 file-max。 -
回滚预案
若出现 EMFILE 或负载飙升,立即执行:
cp /etc/systemd/system/nginx.service.d/nofile.conf.bak /etc/systemd/system/nginx.service.d/nofile.conf
systemctl daemon-reload && systemctl restart nginx
并在配置中心将流量权重降为 0。
拓展思考
- 容器场景:Kubernetes 1.25+ 使用 CRI-O/containerd 时,需同时调整 kubelet 的 --default-ulimit nofile=xxx:xxx 与 pod 的 securityContext.limits,否则 sidecar 日志收集器先打爆 fd。
- 高版本内核优化:5.10+ 开启 CONFIG_PROC_FS=y 后,可通过 /proc/<pid>/fdinfo/ 拿到 fd 的 inode 与打开标志,结合 eBPF 做实时 fd 泄漏追踪。
- 成本权衡:单机 200 万 fd 约消耗 1.2 GB 内核 slab(struct file + dentry),内存预算需提前评估;云主机若开启“超分”,可能触发 oom-killer,建议绑定 2 MB 大页并关闭透明大页。
- 替代方案:若业务为长连接推送,可考虑多监听端口 + SO_REUSEPORT 横向扩展 worker,避免单进程 fd 过百万带来的调度延迟。