仅修改 worker_rlimit_nofile 不生效,必须同步配置系统级限制:通过 systemd(LimitNOFILE)或 limits.conf 设置 nginx 用户的硬限制,并确保 worker_rlimit_nofile 值≤该硬限制,最后重启 Nginx 生效。

只改 worker_rlimit_nofile 不生效,必须让 Nginx 进程实际能拿到足够多的文件描述符。它本身不突破系统限制,只是“申请使用”——而系统是否批准,取决于 nginx 用户的硬限制和启动方式。
确认当前限制值
先看清底数,再决定调多少:
- 查 nginx 主进程运行用户(常见为
nginx或www-data):ps -eo pid,comm,user | grep nginx | head -1 - 查该用户的软/硬限制:
sudo -u nginx bash -c 'ulimit -Sn; ulimit -Hn' - 查 systemd 是否覆盖了限制:
systemctl show nginx | grep LimitNOFILE - 查内核级默认值(供对比):
cat /proc/sys/fs/file-max
同步配置系统级限制
根据你的启动方式选一种,不能跳过:
-
用 systemd 启动(主流):新建
/etc/systemd/system/nginx.service.d/override.conf,写入:
[Service]
LimitNOFILE=65536
然后执行:sudo systemctl daemon-reload && sudo systemctl restart nginx -
用传统方式或 init 脚本启动:编辑
/etc/security/limits.conf,添加两行(用户名需与实际一致):
nginx soft nofile 65536
nginx hard nofile 65536
并确认/etc/pam.d/common-session中有session required pam_limits.so
配置 Nginx 的 worker_rlimit_nofile
在 nginx.conf 的最外层(main 上下文,即 events 块上方、http 块之外)添加:
注意:
– 数值必须 ≤ 系统为 nginx 用户设置的 hard nofile 值,否则启动报错退出;
– 不能写在 http/server/location 内,否则提示 “unknown directive”;
– 修改后必须 restart(不是 reload),因为资源限制只在 worker 进程启动时初始化。
验证是否真正生效
重启后立即检查:
- 取一个 worker 进程 PID:
pgrep -f "nginx: worker" | head -1 - 查看其实际限制:
cat /proc/<pid>/limits | grep "Max open files"</pid> - 输出中 Soft Limit 应等于你设的
65536,Hard Limit 应 ≥ 该值; - 同时检查 Nginx error log,不应出现
setrlimit(RLIMIT_NOFILE)失败类警告。


















