使用pgbench+HAProxy压测PostgreSQL遇端口耗尽问题求助
解决HAProxy端口耗尽导致pgbench短连接压测失败问题
问题场景
使用pgbench结合HAProxy对PostgreSQL主从节点进行连接压测时:
- 执行不带
-C参数的长连接压测命令,5000个客户端可正常运行:
/usr/bin/pgbench -h 127.0.0.1 -p 6432 -U testuser -c 5000 -j 20 -T 60 -S pgbenchdb
- 添加
-C参数(为每个事务建立新连接)后,仅500个客户端就出现连接失败:
/usr/bin/pgbench -h 127.0.0.1 -p 6432 -U testuser -c 500 -C -j 20 -T 60 -S pgbenchdb
报错信息
pgbench报错
pgbench: error: client 230 aborted while establishing connection pgbench: error: connection to server at "127.0.0.1", port 6432 failed: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request.
HAProxy报错
Connect() failed for backend test6432: no free ports. message repeated 499 times: [ Connect() failed for backend test6432: no free ports.]
环境信息
- HAProxy版本:
HAProxy version 2.4.22-0ubuntu0.22.04.2 2023/08/14 - 系统环境:
Linux HAPROXY06S03 5.15.0-91-generic #101-Ubuntu SMP Tue Nov 14 13:30:08 UTC 2023 x86_64 x86_64 x86_64 GNU/Linux - HAProxy配置:
global log /dev/log local0 log /dev/log local1 notice chroot /var/lib/haproxy stats socket /run/haproxy/admin.sock mode 660 level admin expose-fd listeners stats timeout 30s user haproxy group haproxy daemon defaults timeout connect 60s timeout client 720m timeout server 720m listen stats mode http bind *:6433 stats enable stats uri /stats stats refresh 120s stats auth admin:*** listen test6432 log 127.0.0.1:514 local0 notice bind *:6432 mode tcp option tcp-check tcp-check expect string MASTER default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions server testdb01 172.10.20.51:5432 maxconn 10000 check port 5400 server testdb02 172.10.20.52:5432 maxconn 10000 check port 5400
解决方案
端口耗尽的核心原因是短连接场景下,HAProxy作为客户端连接后端PostgreSQL时,本地源端口被快速耗尽,且默认内核参数下端口回收速度较慢。以下是针对性解决措施:
1. 调整Linux内核端口参数
编辑/etc/sysctl.conf文件,添加或修改以下参数,扩大可用端口范围并加快端口回收:
# 扩大本地可用端口范围 net.ipv4.ip_local_port_range = 1024 65535 # 允许复用TIME-WAIT状态的端口用于新的TCP连接 net.ipv4.tcp_tw_reuse = 1 # 缩短TIME-WAIT状态的超时时间 net.ipv4.tcp_fin_timeout = 30 # 禁用tcp_tw_recycle(NAT环境下会导致连接异常) net.ipv4.tcp_tw_recycle = 0
执行以下命令使配置生效:
sysctl -p
2. 优化HAProxy配置
在HAProxy的global段添加以下参数,提升连接处理能力:
global # 扩大HAProxy最大连接数 maxconn 32768 # 调整缓冲区大小,适配大流量场景 tune.bufsize 16384 # 提升SSL相关性能(若使用SSL则配置,否则可忽略) tune.ssl.default-dh-param 2048
如果HAProxy服务器拥有多个网卡IP,可在listen test6432段添加source指令,让HAProxy使用多个源IP连接后端,大幅提升可用端口总数:
listen test6432 # 指定多个本地IP作为连接后端的源IP(替换为实际可用IP) source 172.10.20.3 172.10.20.4 # 其他原有配置...
3. 压测参数调整(临时缓解)
若暂时无法修改内核或HAProxy配置,可适当降低pgbench的线程数(-j参数),减少并发连接创建的频率:
/usr/bin/pgbench -h 127.0.0.1 -p 6432 -U testuser -c 500 -C -j 10 -T 60 -S pgbenchdb
内容的提问来源于stack exchange,提问作者Багир Гварамадзе
相关产品推荐
相关产品推荐

