直接调大 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 运行用户:运行
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"
必须同步放宽系统级 nofile 限制
只改 Nginx 配置无效,必须打通底层权限链路。根据部署方式选一种,不能混用:
-
用 systemd(主流推荐):创建
/etc/systemd/system/nginx.service.d/override.conf,写入:
[Service]<br>LimitNOFILE=1048576
然后执行sudo systemctl daemon-reload && sudo systemctl restart nginx -
不用 systemd(如手动启停或旧 init):编辑
/etc/security/limits.conf,添加两行(用户名需匹配):
nginx soft nofile 1048576<br>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 给日志、上游连接、临时文件等 - 检查并调优内核参数:
fs.file-max建议 ≥ 2× 总句柄需求(如设为 2097152);net.core.somaxconn建议 ≥ 65535 - 验证是否落地:重启后执行
cat /proc/$(pgrep -f "nginx: worker" | head -1)/limits | grep "Max open files",Soft Limit 应与配置一致



















