worker_rlimit_nofile必须与系统级limits、systemd配置及内核参数联动调优,设为131072时worker_connections建议90000,并通过/proc/<pid>/limits验证生效。

非 root 用户运行 Nginx 时,默认无法突破系统对普通进程的文件句柄限制(如 ulimit -n 1024),即使配置了 worker_rlimit_nofile,也常因底层权限或启动方式问题失效。关键在于:该指令仅告诉 Nginx 主进程“希望子进程打开多少句柄”,但真正生效依赖于**启动前的进程资源限制**和**用户级持久化配置**,而非 Nginx 自身能越权提升。
确认当前限制来源
Nginx 启动时继承 shell 的 ulimit 值。非 root 用户无法在运行时调高 soft limit 超过 hard limit,而 hard limit 通常由系统策略(如 /etc/security/limits.conf 或 systemd user scope)设定。直接在 nginx.conf 中写 worker_rlimit_nofile 65535; 不会自动绕过这些限制。
- 检查当前用户限制:
ulimit -n(soft)、ulimit -Hn(hard) - 查看 Nginx 主进程实际限制:
cat /proc/$(pgrep nginx | head -1)/limits | grep "Max open files" - 若输出中 Max open files 的 soft 值远低于配置值,说明启动前限制已卡死
为非 root 用户设置持久化 limits
必须在 Nginx 启动前,让系统赋予该用户足够高的 hard limit。推荐使用 systemd 用户服务(现代 Linux 发行版默认支持):
- 创建
/etc/systemd/system/nginx@.service(模板服务)或针对具体用户:/etc/systemd/system/nginx-user.service,内容包含: -
[Service]LimitNOFILE=65535User=nginxuserExecStart=/usr/sbin/nginx -g "daemon off;" - 重载配置:
systemctl daemon-reload,然后启用:systemctl enable --now nginx-user - 避免使用 /etc/security/limits.conf —— 它对 systemd 启动的服务常不生效(尤其 session 类型)
正确配置 Nginx 的 worker_rlimit_nofile
该指令需放在 nginx.conf 的 main 上下文(即最外层),且数值不能超过启动时进程的 hard limit:
- 示例配置(/etc/nginx/nginx.conf):
user nginxuser;worker_rlimit_nofile 65535;-
events {worker_connections 65535;} - 注意:
worker_connections应 ≤worker_rlimit_nofile,否则 worker 进程可能因无法分配足够句柄而报错
验证是否真正生效
重启服务后,分两步验证:
- 查主进程限制:
cat /proc/$(pgrep nginx | head -1)/limits | grep "Max open files"→ soft 和 hard 都应 ≥ 65535 - 查 worker 进程限制:
cat /proc/$(pgrep nginx | tail -1)/limits | grep "Max open files"→ 应与主进程一致(因 fork 继承) - 检查 Nginx 错误日志是否有
open() "/path" failed (24: Too many open files)类报错 - 用
ss -s或lsof -u nginxuser | wc -l观察实际打开句柄数增长是否突破原限制


















