HAProxy负载均衡配置
约 1717 字大约 6 分钟
haproxyload-balancing
2025-07-12
概述
HAProxy(High Availability Proxy)是一款高性能的TCP/HTTP负载均衡器和代理服务器,广泛应用于高流量网站和微服务架构。它以稳定性、丰富的功能和极高的性能著称,单实例可处理数十万并发连接。
架构概览
配置文件结构
HAProxy配置分为四个主要部分:
haproxy.cfg
├── global # 全局设置(进程级)
├── defaults # 默认参数(可被frontend/backend覆盖)
├── frontend # 前端(监听端口,接收请求)
├── backend # 后端(服务器组)
└── listen # frontend + backend的简写形式Global配置
global
# 进程管理
daemon
maxconn 50000 # 最大并发连接
nbthread 4 # 工作线程数
# 日志
log /dev/log local0 info
log /dev/log local1 notice
# 安全
user haproxy
group haproxy
chroot /var/lib/haproxy
# SSL
ssl-default-bind-ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256
ssl-default-bind-ciphersuites TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
# 性能调优
tune.ssl.default-dh-param 2048
tune.bufsize 32768
tune.maxrewrite 8192
# Stats Socket(用于运行时管理)
stats socket /var/run/haproxy.sock mode 660 level admin
stats timeout 30sDefaults配置
defaults
mode http # http/tcp模式
log global
option httplog # 详细HTTP日志
option dontlognull # 不记录健康检查日志
option http-server-close # 服务端连接关闭
option forwardfor except 127.0.0.0/8 # X-Forwarded-For
option redispatch # 服务器不可用时重新分配
retries 3 # 连接重试次数
# 超时设置
timeout connect 5s # 连接后端超时
timeout client 30s # 客户端超时
timeout server 30s # 服务端超时
timeout http-request 10s # HTTP请求超时
timeout http-keep-alive 10s # Keep-alive超时
timeout queue 30s # 排队超时
timeout check 5s # 健康检查超时
# 错误处理
errorfile 400 /etc/haproxy/errors/400.http
errorfile 403 /etc/haproxy/errors/403.http
errorfile 503 /etc/haproxy/errors/503.httpFrontend配置
frontend http-in
bind *:80
bind *:443 ssl crt /etc/ssl/certs/example.pem alpn h2,http/1.1
# HTTP到HTTPS重定向
http-request redirect scheme https unless { ssl_fc }
# ACL规则
acl is_api path_beg /api/
acl is_static path_beg /static/ /images/ /css/ /js/
acl is_websocket hdr(Upgrade) -i websocket
acl is_admin path_beg /admin
acl src_internal src 10.0.0.0/8 172.16.0.0/12
# 安全headers
http-response set-header X-Frame-Options DENY
http-response set-header X-Content-Type-Options nosniff
http-response set-header Strict-Transport-Security "max-age=63072000"
# 路由到不同后端
use_backend api-servers if is_api
use_backend static-servers if is_static
use_backend ws-servers if is_websocket
use_backend admin-servers if is_admin src_internal
default_backend web-serversBackend配置
backend web-servers
balance roundrobin
option httpchk GET /health HTTP/1.1\r\nHost:\ localhost
http-check expect status 200
# Cookie会话保持
cookie SERVERID insert indirect nocache
server web1 10.0.0.1:8080 check cookie web1 weight 3 maxconn 1000
server web2 10.0.0.2:8080 check cookie web2 weight 3 maxconn 1000
server web3 10.0.0.3:8080 check cookie web3 weight 2 maxconn 800
server web-backup 10.0.0.4:8080 check backup
backend api-servers
balance leastconn
option httpchk GET /api/health
# 重试策略
retries 2
retry-on conn-failure empty-response response-timeout
server api1 10.0.1.1:8080 check inter 3s fall 3 rise 2
server api2 10.0.1.2:8080 check inter 3s fall 3 rise 2
backend static-servers
balance uri
hash-type consistent
server static1 10.0.2.1:80 check
server static2 10.0.2.2:80 check
backend ws-servers
balance source
timeout server 3600s # WebSocket长连接
timeout tunnel 3600s
server ws1 10.0.3.1:8080 check
server ws2 10.0.3.2:8080 checkACL规则详解
# ACL示例
acl is_api path_beg /api/
acl is_mobile hdr_sub(User-Agent) -i mobile android iphone
acl is_json hdr(Content-Type) -i application/json
acl rate_limit sc_http_req_rate(0) gt 100
acl blacklisted src -f /etc/haproxy/blacklist.txt
acl office_hours date_hour 9-18
acl weekend date_wday 6 7
# 组合ACL
use_backend mobile-api if is_api is_mobile
http-request deny if blacklisted
http-request deny if rate_limit !src_internal健康检查
backend app-servers
# HTTP健康检查
option httpchk GET /health HTTP/1.1\r\nHost:\ app.example.com
http-check expect status 200
http-check expect string "status":"ok"
# 检查参数
server app1 10.0.0.1:8080 check inter 5s fall 3 rise 2
# inter: 检查间隔
# fall: 连续失败N次标记为down
# rise: 连续成功N次标记为up
# TCP健康检查(适用于非HTTP服务)
# option tcp-check
# tcp-check connect
# tcp-check send PING\r\n
# tcp-check expect string +PONG
# 外部Agent检查
# server app1 10.0.0.1:8080 agent-check agent-inter 5s agent-port 9999会话保持
# Cookie会话保持
backend web
balance roundrobin
cookie SERVERID insert indirect nocache httponly secure
server web1 10.0.0.1:80 cookie s1 check
server web2 10.0.0.2:80 cookie s2 check
# Source IP会话保持
backend web
balance source
hash-type consistent
server web1 10.0.0.1:80 check
server web2 10.0.0.2:80 check
# Stick Table会话保持
backend web
stick-table type ip size 200k expire 30m
stick on src
server web1 10.0.0.1:80 check
server web2 10.0.0.2:80 checkSSL卸载
frontend https-in
bind *:443 ssl crt /etc/ssl/certs/ alpn h2,http/1.1
# 客户端证书验证(mTLS)
# bind *:443 ssl crt /etc/ssl/certs/server.pem ca-file /etc/ssl/certs/ca.pem verify required
# 传递SSL信息给后端
http-request set-header X-Forwarded-Proto https
http-request set-header X-SSL-Client-Verify %[ssl_c_verify]
http-request set-header X-SSL-Client-DN %{+Q}[ssl_c_s_dn]
default_backend web-servers
backend web-servers
# 后端使用HTTP(SSL已终止)
server web1 10.0.0.1:80 checkStats监控页面
listen stats
bind *:8404
stats enable
stats uri /stats
stats refresh 10s
stats admin if TRUE # 允许管理操作
stats auth admin:secure_password
stats hide-version
stats show-legends限流(Rate Limiting)
frontend http-in
bind *:80
# 定义stick-table用于限流
stick-table type ip size 100k expire 60s store http_req_rate(10s),conn_cur
# 跟踪请求速率
http-request track-sc0 src
# 超过100 req/10s则拒绝
acl rate_abuse sc_http_req_rate(0) gt 100
http-request deny deny_status 429 if rate_abuse
# 超过20并发连接则拒绝
acl too_many_conns sc_conn_cur(0) gt 20
http-request deny deny_status 429 if too_many_conns
default_backend web-serversHAProxy vs Nginx对比
| 特性 | HAProxy | Nginx |
|---|---|---|
| 核心定位 | 负载均衡器 | Web服务器+反向代理 |
| L4负载均衡 | 原生支持 | stream模块支持 |
| L7负载均衡 | 强大的ACL系统 | location匹配 |
| 健康检查 | 丰富(HTTP/TCP/Agent) | 被动检查(Plus版有主动) |
| 会话保持 | Cookie/Source/Stick Table | ip_hash/cookie |
| 静态文件 | 不支持 | 原生支持 |
| Stats/监控 | 内置Web界面 | stub_status(基础) |
| 配置热更新 | 运行时API | reload |
| SSL终止 | 支持 | 支持 |
| WebSocket | 支持 | 支持 |
| 最佳场景 | 纯负载均衡 | Web服务+反向代理 |
高可用部署
# Keepalived配置(主节点)
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass mypassword
}
virtual_ipaddress {
192.168.1.100/24
}
track_script {
chk_haproxy
}
}
vrrp_script chk_haproxy {
script "pidof haproxy"
interval 2
weight -20
}总结
HAProxy以其强大的负载均衡能力、灵活的ACL规则和丰富的健康检查机制,成为高可用架构中的核心组件。它在L4/L7负载均衡、会话保持、限流等方面的功能比Nginx更加专业和精细。在实际部署中,HAProxy常与Keepalived配合实现高可用,或与Nginx协同工作(Nginx处理静态文件,HAProxy负责动态请求分发)。
贡献者
更新日志
2026/3/14 13:09
查看所有更新日志
9f6c2-feat: organize wiki content and refresh site setup于