worker_connections必须置于events块内,且需同步放开系统文件描述符限制、配置worker_rlimit_nofile、调优net.core.somaxconn等内核参数,否则将静默失效或报“too many open files”。

直接改 worker_connections 却没生效,八成不是语法写错,而是它压根没被 Nginx 读进去——这个参数对位置、层级、系统配合极度敏感,错一处就静默失效或报错启动失败。
语法错误:只能放在 events 块里
这是最常踩的坑:worker_connections 必须且只能出现在 events { ... } 块内。写在 http、server、location 甚至主配置顶部,Nginx 启动时会直接报错:
nginx: [emerg] "worker_connections" directive is not allowed here- 或者
nginx: configuration file /etc/nginx/nginx.conf test failed
正确写法示例:
events {
worker_connections 8192;
}
生效失败:系统文件描述符没放开
即使语法完全正确,worker_connections 65535 也可能实际只按 1024 运行。因为 Linux 默认单进程最多打开 1024 个文件描述符(fd),而每个连接至少占 1 个 fd。Nginx 检测到资源不足,会自动降级或警告:
- 日志中出现
worker_connections exceed open file resource limit: 1024 - 启动后查
cat /proc/$(pgrep nginx)/limits | grep "Max open files",发现 soft/hard 值仍是 1024
必须同步做三件事:
- 修改
/etc/security/limits.conf,为运行用户(如www-data)设soft nofile 65536和hard nofile 65536 - 若用 systemd,还需在
/etc/systemd/system/nginx.service.d/override.conf中加LimitNOFILE=65536 - 重启 nginx(不是 reload)让新 limits 生效
生效失败:缺了 worker_rlimit_nofile 声明
worker_rlimit_nofile 是 Nginx 进程自己向系统“申请”句柄上限的指令,必须写在 main 上下文(即 events 和 http 块之外的顶层)。它不等于 worker_connections,但必须 ≥ 后者,否则 Nginx 不会真正启用你设的连接数。
- 漏写该指令,即使系统 ulimit 调高了,Nginx 仍可能卡在旧限制上
- 建议值:比
worker_connections × worker_processes高 10%~20%,例如worker_rlimit_nofile 65536;
错误示范:http {
worker_rlimit_nofile 65536; ← 错!不能放 http 块里
...
}
正确位置应在 user、worker_processes 之后,events 之前。
生效失败:内核网络队列未扩容
即便 Nginx 和系统都准备好了,新 TCP 握手请求也可能在进入 Nginx 前就被内核丢弃——因为监听队列(net.core.somaxconn)太小。这时你不会在 Nginx 日志里看到错误,但客户端表现为:
- Connection refused 或 TCP 超时
-
netstat -s | grep "listen overflows"显示溢出次数持续上升
需修改 /etc/sysctl.conf 并执行 sysctl -p:
net.core.somaxconn = 65535net.core.netdev_max_backlog = 25000fs.file-max = 2000000











