Nginx透明反向代理HTTP长连接异常及端口占用问题排查
Nginx透明反向代理Keep-Alive失效(Address already in use)问题解决
问题描述
配置Nginx透明反向代理后,单次curl请求正常,但HTTP Keep-Alive无法工作,请求流程如下:
client ---> nginx ----> Server (GET) client <--- nginx <---- Server (200 OK) client ---> nginx ----> Server (GET failed)
Nginx日志报错:failed (98: Address already in use) while connecting to upstream
当前nginx.conf配置:
upstream proxy { server proxy; } server { listen 80; proxy_bind $remote_addr:$remote_port transparent; server_name myhomepage.com; location / { proxy_set_header Host $host; proxy_http_version 1.1; proxy_set_header Connection ""; proxy_pass http://proxy; } }
要求必须保留$remote_port参数
问题原因
使用proxy_bind $remote_addr:$remote_port强制Nginx绑定客户端的源IP和端口连接上游时,当客户端通过Keep-Alive复用同一个源端口发起后续请求,该端口可能还处于TCP的TIME_WAIT状态(上游端关闭连接后,端口会暂时保留一段时间),导致Nginx无法再次绑定该端口,触发Address already in use错误。同时Nginx默认的连接池管理机制没有针对这种绑定固定客户端端口的场景做适配。
解决方案
1. 启用上游连接的TCP保活
在server块中添加:
proxy_socket_keepalive on;
该配置会让Nginx与上游服务器的TCP连接启用保活机制,减少连接被主动关闭进入TIME_WAIT的概率,同时复用已有连接。
2. 调整连接超时参数
在location块中补充超时配置,避免连接长时间闲置被关闭:
proxy_connect_timeout 10s; proxy_send_timeout 60s; proxy_read_timeout 60s;
3. 优化上游连接复用配置
修改upstream块,启用连接池复用并调整相关参数:
upstream proxy { server proxy; keepalive 32; # 保留32个空闲长连接 keepalive_timeout 60s; # 空闲连接超时时间 keepalive_requests 1000; # 单个连接处理的最大请求数 }
4. 调整系统TCP参数(可选)
如果上述配置仍无法解决,可调整系统内核参数,缩短TIME_WAIT状态的端口保留时间:
# 临时生效 sysctl -w net.ipv4.tcp_tw_reuse=1 sysctl -w net.ipv4.tcp_fin_timeout=30 # 永久生效,写入/etc/sysctl.conf echo "net.ipv4.tcp_tw_reuse=1" >> /etc/sysctl.conf echo "net.ipv4.tcp_fin_timeout=30" >> /etc/sysctl.conf sysctl -p
注意:tcp_tw_recycle在现代内核中已被废弃,不建议启用。
调整后的完整配置示例
upstream proxy { server proxy; keepalive 32; keepalive_timeout 60s; keepalive_requests 1000; } server { listen 80; proxy_bind $remote_addr:$remote_port transparent; server_name myhomepage.com; proxy_socket_keepalive on; location / { proxy_set_header Host $host; proxy_http_version 1.1; proxy_set_header Connection ""; proxy_connect_timeout 10s; proxy_send_timeout 60s; proxy_read_timeout 60s; proxy_pass http://proxy; } }
内容的提问来源于stack exchange,提问作者scroh
相关产品推荐
相关产品推荐

