已调somaxconn和ulimit仍遇Nginx上游连接Too many open files错误,求排查
Nginx "Too many open files" 错误排查与解决
问题描述
Nginx日志持续报错:38341 socket() failed (24: Too many open files) while connecting to upstream,已调高服务器somaxconn参数、ulimit值,修改系统全局限制、nginx.conf及网站配置文件后问题依旧,重启Nginx偶尔能恢复正常,但网站API响应极慢。
已尝试操作
- 在
/etc/sysctl.conf中添加配置:
并执行fs.file-max = 2097152 net.core.somaxconn=500000 vm.max_map_count = 250000 net.ipv4.ip_local_port_range = 1024 500000sysctl -w net.core.somaxconn=500000临时生效 - 在
/etc/security/limits.conf中添加:root hard nofile 500000 root soft nofile 500000
服务器CPU信息
lscpu Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Byte Order: Little Endian CPU(s): 24 On-line CPU(s) list: 0-23 Thread(s) per core: 2 Core(s) per socket: 12 Socket(s): 1 NUMA node(s): 1 Vendor ID: GenuineIntel BIOS Vendor ID: Intel CPU family: 6 Model: 106 Model name: Intel(R) Xeon(R) Silver 4310 CPU @ 2.10GHz BIOS Model name: Intel(R) Xeon(R) Silver 4310 CPU @ 2.10GHz Stepping: 6 CPU MHz: 3300.000 CPU max MHz: 3300.0000 CPU min MHz: 800.0000 BogoMIPS: 4200.00 Virtualization: VT-x L1d cache: 48K L1i cache: 32K L2 cache: 1280K L3 cache: 18432K NUMA node0 CPU(s): 0-23
排查与解决步骤
1. 确认Nginx进程实际生效的文件句柄限制
- 找到Nginx主进程PID:
ps aux | grep nginx | grep master - 查看该进程的文件句柄限制:
如果显示数值远低于500000,说明系统限制未生效到Nginx进程。cat /proc/<PID>/limits | grep "Max open files"
2. 强制Nginx加载文件句柄限制
针对systemd管理的Nginx
编辑/etc/systemd/system/nginx.service或/lib/systemd/system/nginx.service,在[Service]段添加:
LimitNOFILE=500000 LimitNPROC=500000
重新加载systemd并重启Nginx:
systemctl daemon-reload systemctl restart nginx
针对init脚本启动的Nginx
在Nginx启动脚本(如/etc/init.d/nginx)开头添加:
ulimit -n 500000 ulimit -u 500000
3. 优化Nginx自身worker进程配置
编辑nginx.conf,调整以下参数:
worker_processes 24; # 匹配服务器CPU核心数 worker_rlimit_nofile 500000; # 覆盖进程级文件句柄限制 events { worker_connections 100000; # 单worker最大连接数,按需调整 use epoll; # 启用高效事件驱动模型 multi_accept on; # 允许worker一次性接收所有新连接 }
重启Nginx生效。
4. 检查上游服务的文件句柄限制
错误发生在连接上游时,需排查后端服务(如PHP-FPM、Tomcat、API服务)的文件句柄是否不足:
- 找到上游服务进程PID:
# 以PHP-FPM为例 ps aux | grep php-fpm - 查看进程文件句柄限制:
cat /proc/<PID>/limits | grep "Max open files" - 按Nginx的调整方式,给上游服务设置足够的文件句柄限制。
5. 排查句柄泄漏与连接堆积
- 查看Nginx进程当前打开的文件句柄数量:
lsof -p <Nginx-Master-PID> | wc -l lsof -p <Nginx-Worker-PID> | wc -l - 查看具体的连接状态:
lsof -p <PID> | grep -E "(TCP|UDP)" - 若存在大量TIME_WAIT连接,添加内核优化参数到
/etc/sysctl.conf:
执行net.ipv4.tcp_tw_reuse = 1 net.ipv4.tcp_fin_timeout = 30 net.ipv4.tcp_max_tw_buckets = 5000sysctl -p生效。
6. 验证配置生效
重启服务器后,检查:
- 系统全局文件句柄限制:
sysctl fs.file-max ulimit -n - Nginx进程的文件句柄限制:
cat /proc/<Nginx-PID>/limits | grep "Max open files"
内容的提问来源于stack exchange,提问作者Abhishek
相关产品推荐
相关产品推荐

