Nginx 的 worker_connections 默认上限由系统文件描述符限制决定,需同步调整 ulimit、/etc/security/limits.conf、systemd LimitNOFILE 及 nginx.conf 中 events 块配置,并通过 nginx -t 和 /proc/$(pidof nginx)/limits 验证生效。

安装 Nginx 后,worker_connections 的默认最大值不是由 Nginx 自身硬编码决定的,而是受限于操作系统对单个进程可打开文件描述符(file descriptor)数量的限制。因此,要提高 worker_connections,必须同时调整系统级限制和 Nginx 配置。
查看当前系统允许的最大文件描述符数
每个 Nginx worker 进程需要为每个连接分配一个文件描述符(如客户端 socket、日志文件、上游连接等),所以 worker_connections 不能超过该进程能打开的文件描述符上限。
运行以下命令查看当前 shell 限制:
ulimit -n通常默认是 1024,这会直接限制 worker_connections 无法设为更高值(即使配置写了 4096,启动时也会报错或自动截断)。
临时提升单次会话的文件描述符限制
仅用于测试或调试,重启后失效:
- 执行 ulimit -n 65536
- 再启动 Nginx(确保是在该 shell 中启动,或用 systemctl --no-block start nginx 不适用此方式)
永久修改系统级限制(推荐)
需修改两个位置:
-
/etc/security/limits.conf:添加两行(适用于使用 PAM 的系统,如 CentOS/RHEL/Ubuntu)
nginx soft nofile 65536
nginx hard nofile 65536
若 Nginx 以www-data用户运行,则替换为www-data -
Nginx 服务单元配置(systemd):编辑 /etc/systemd/system/nginx.service.d/override.conf(若不存在则新建):
[Service]
LimitNOFILE=65536
生效前需重载 systemd 并重启 Nginx:
systemctl daemon-reloadsystemctl restart nginx
在 nginx.conf 中设置 worker_connections
找到 events 块,修改或添加:
worker_connections 4096;
}
注意:
- 该值建议 ≤ 单个 worker 进程的 nofile 限制(如设为 65536,则 worker_connections 可设到 65535,留一个给日志等其他用途)
- 若启用了 multi_accept on;,Nginx 会尝试一次性接受多个连接,对 fd 消耗略高,也应预留余量
不复杂但容易忽略的是:只改 Nginx 配置而不调系统限制,Nginx 启动会失败或静默降级。验证是否生效,可用 nginx -t 检查语法,再用 cat /proc/$(pidof nginx)/limits | grep "Max open files" 查看实际生效值。










