worker_rlimit_nofile 不能突破系统限制,仅让 Nginx 主进程申请更高软限制,实际生效取决于系统级配置;需依次验证用户、systemd、运行中 worker 的文件描述符限制,并同步调整 systemd 或 limits.conf、正确设置 worker_rlimit_nofile(≤hard nofile)、worker_connections(70%~85% of rlimit)及内核参数 fs.file-max 等。

worker_rlimit_nofile 本身不能“突破”系统限制,它只是让 Nginx 主进程在启动 worker 前主动申请更高的文件描述符软限制——但这个申请必须被操作系统允许。真正起决定作用的是系统级配置,Nginx 配置只是最后一环。
先查清当前哪一级限制卡住了
别凭经验改配置,按顺序验证真实值:
- 确认 Nginx 运行用户:运行 ps -eo pid,comm,user | grep nginx | grep master,常见为 www-data 或 nginx
- 查该用户的软硬限制:执行 sudo -u nginx bash -c "ulimit -Sn; ulimit -Hn"
- 查 systemd 服务限制(若用 systemd):运行 systemctl show nginx | grep LimitNOFILE
- 查运行中 worker 进程实际值:取一个 worker PID,执行 cat /proc/PID/limits | grep "Max open files"
同步调整系统级限制(必须做)
根据部署方式选一种,不能混用,也不能跳过:
-
用 systemd(主流推荐):创建 /etc/systemd/system/nginx.service.d/override.conf,写入:
[Service]
LimitNOFILE=1048576
再执行 sudo systemctl daemon-reload && sudo systemctl restart nginx -
不用 systemd(如手动启停或旧 init):编辑 /etc/security/limits.conf,添加两行(用户名需匹配):
nginx soft nofile 1048576
nginx hard nofile 1048576
并确认 /etc/pam.d/common-session 中有 session required pam_limits.so
正确配置 Nginx 的 worker_rlimit_nofile
这个指令只在 main 上下文生效,位置和数值都关键:
- 必须放在 nginx.conf 最外层,即 events 和 http 块之外、之前
- 数值不能超过上一步设置的 hard nofile,建议设为硬限制的 90% 左右(如 hard 是 1048576,这里设 943718)
- 典型写法:worker_rlimit_nofile 943718;
- 注意:仅 restart 生效,reload 不会重设 worker 进程的资源限制
配套调优 worker_connections 和内核参数
开了大门,还得算清楚能进多少人、系统撑不撑得住:
- 在 events 块中设 worker_connections,建议为 worker_rlimit_nofile 的 70%~85%(例如 943718 → 设 700000),预留 fd 给日志、上游连接、临时文件等
- 检查并调大内核总容量:
在 /etc/sysctl.conf 中添加:
fs.file-max = 2097152
fs.epoll.max_user_watches = 524288
执行 sudo sysctl -p 加载 - 验证最终效果:重启后再次检查 /proc/PID/limits,确保 Soft Limit 和 Hard Limit 均达到预期值



















