最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Nginx 如何在配置文件中设置单个进程允许打开的最大文件描述符数
时间:2026-08-13 12:47:49 编辑:袖梨 来源:一聚教程网
worker_rlimit_nofile必须置于nginx.conf全局块(events和http块之外),值需≤系统硬限制并同步配置limits.conf、systemd LimitNOFILE及内核fs.file-max,且worker_connections应为其70%~80%,最后通过/proc/PID/limits验证生效。
在 Nginx 配置文件中设置单个 worker 进程允许打开的最大文件描述符数,用的是 worker_rlimit_nofile 指令,它必须放在 全局块(即 http 块之外、配置文件最外层),不能写在 events 或 http 块内部。
正确位置和写法
打开 nginx.conf,在 events { ... } 上方、http { ... } 外侧的全局作用域中添加:
worker_rlimit_nofile 65535;
例如:
user nginx;worker_processes auto;worker_rlimit_nofile 65535;# ← 就放这里events { use epoll; worker_connections 65535; }
http { ... }
这个值不是孤立生效的
worker_rlimit_nofile 只是告诉 Nginx “我允许你开这么多 fd”,但实际能否达到,取决于启动时进程拿到的操作系统级限制。如果 ulimit -n 只有 1024,那即使配了 65535,Nginx 启动后也拿不到那么多。
- 确保启动 Nginx 的用户(如 nginx)在
/etc/security/limits.conf中有对应设置:nginx soft nofile 65535nginx hard nofile 65535 - 如果用自定义脚本启动(比如
/etc/init.d/nginx),需在执行 nginx 命令前加:ulimit -n 65535 - 该值不能超过系统总上限
fs.file-max,建议同步调高:echo 'fs.file-max = 262144' >> /etc/sysctl.conf && sysctl -p
配套必须检查的配置项
仅设 worker_rlimit_nofile 不够,还需匹配其他参数:
-
worker_connections应 ≤worker_rlimit_nofile(推荐留余量,比如设 65535 时,worker_connections 设 65535 或略低) - 若启用了
open_file_cache,其max=值也不应超过worker_rlimit_nofile - 重启前务必运行
nginx -t校验语法,再nginx -s reload生效
验证是否生效
启动后查主进程 PID,再看内核实际限制:
ps -ef | grep nginx | grep -v grep | head -1 | awk '{print $2}' | xargs -I{} cat /proc/{}/limits | grep "Max open files"
输出类似 Max open files 65535 65535 才算真正生效。