必须三层对齐系统用户硬限制、systemd(或pam)服务限制、nginx配置的worker_rlimit_nofile,且该指令仅能置于main上下文;数值需合理配比,验证须通过/proc/pid/limits及日志确认。

单独改 worker_rlimit_nofile 无法突破限制,它只是让 worker 进程“申请”更高软限制,是否生效完全取决于系统是否允许。必须三层对齐:系统用户硬限制、systemd(或 PAM)服务限制、Nginx 配置本身,缺一不可。
必须放在 main 上下文
该指令只能写在 nginx.conf 最外层,即 events 块和 http 块之外、文件开头附近。常见错误是把它塞进 server 或 http 块里,会导致启动报错:
nginx: [emerg] "worker_rlimit_nofile" directive is not allowed here
正确写法示例:
worker_processes auto;<br>worker_rlimit_nofile 65535;
后面紧跟
events { ... } 块。
系统级限制必须同步放宽
Nginx 启动时继承运行用户的 ulimit,若系统没放行,配置值会被静默截断或直接拒绝。按部署方式选一种方式调整:
- 用 systemd(主流):新建
/etc/systemd/system/nginx.service.d/override.conf,写入[Service]<br>LimitNOFILE=65535
然后执行sudo systemctl daemon-reload && sudo systemctl restart nginx - 不用 systemd:编辑
/etc/security/limits.conf,添加两行(用户名按实际替换,如nginx或www-data):nginx soft nofile 65535<br>nginx hard nofile 65535
并确认/etc/pam.d/common-session包含session required pam_limits.so
数值要合理配比,不能顶格设
worker_rlimit_nofile 是资源池上限,worker_connections 才是实际处理连接的业务上限,二者必须留出余量:
-
worker_rlimit_nofile建议设为系统hard nofile的 90% 左右(例如 hard 是 65535,这里设 59000) -
worker_connections推荐设为worker_rlimit_nofile的 70%~85% - 反向代理或高频 DNS 解析场景(如
proxy_pass http://$host),每个请求可能占用多个 fd,建议按 1.2~1.5 倍worker_connections估算所需句柄数
验证是否真正生效
改完必须验证,不能只信配置文件:
- 查运行中 worker 进程的实际限制:
cat /proc/$(pgrep nginx | head -1)/limits | grep "Max open files"
输出的 Soft Limit 应与你配置的值一致 - 压测时观察
error.log是否还有"open() failed (24: Too many open files)" - 用
lsof -p $(pgrep nginx | head -1) | wc -l查看当前打开句柄数,应稳定在预期范围内











