haproxy 详解,四层、七层负载均衡配置,haproxy + keepalived示例

HAProxy 是一款高性能的开源负载均衡器和反向代理软件,同时支持 四层(TCP)七层(HTTP) 负载均衡。

一、核心概念对比

特性四层负载均衡(Layer 4)七层负载均衡(Layer 7)
工作层级TCP/UDP 传输层HTTP/HTTPS 应用层
转发依据IP + 端口URL、Cookie、请求头等
性能更高(不解析应用层内容)稍低(需解析 HTTP 报文)
适用场景数据库、邮件、TLS 直通Web 服务、API 网关
健康检查TCP 连接检测HTTP 状态码/内容检测
会话保持Source IP 哈希Cookie 插入、IP 哈希

二、四层(TCP)负载均衡配置

四层模式下,HAProxy 只做 IP+端口转发,不解析应用层协议内容。

global
    log /dev/log local0
    log /dev/log local1 notice
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660 level admin
    stats timeout 30s
    user haproxy
    group haproxy
    daemon
    maxconn 4000

defaults
    log     global
    mode    tcp            # 四层模式
    option  tcplog
    option  dontlognull
    retries 3
    timeout connect 5000ms
    timeout client  50000ms
    timeout server  50000ms

frontend tcp_frontend
    bind *:3306            # 监听 MySQL 默认端口
    default_backend tcp_servers

backend tcp_servers
    balance roundrobin     # 轮询算法
    server db1 192.168.1.10:3306 check inter 2000 fall 3 rise 5
    server db2 192.168.1.11:3306 check inter 2000 fall 3 rise 5
    server db_backup 192.168.1.12:3306 backup

关键参数说明:

  • mode tcp:声明为四层负载均衡
  • balance roundrobin:轮询分配请求
  • check:启用健康检查
  • inter 2000:健康检查间隔 2 秒
  • fall 3:连续 3 次失败标记为 DOWN
  • rise 5:连续 5 次成功标记为 UP
  • backup:仅在其他服务器全部不可用时启用

三、七层(HTTP)负载均衡配置

七层模式下,HAProxy 可以解析 HTTP 报文,实现基于 URL、Host、Cookie 等内容的精细路由。

global
    log /dev/log local0
    maxconn 4000
    daemon

defaults
    log     global
    mode    http           # 七层模式
    option  httplog
    option  dontlognull
    retries 3
    timeout connect 5000ms
    timeout client  50000ms
    timeout server  50000ms

# ============ 前端配置 ============
frontend http_frontend
    bind *:80
    mode http

    # 定义 ACL 规则
    acl is_api    path_beg /api
    acl is_static path_beg /static
    acl is_ws     hdr(Upgrade) -i websocket

    # 根据 ACL 规则路由到不同后端
    use_backend api_servers    if is_api
    use_backend static_servers if is_static
    use_backend ws_servers     if is_ws

    # 默认后端
    default_backend web_servers

# ============ 后端配置 ============
backend web_servers
    mode http
    balance leastconn       # 最少连接数算法
    option httpchk GET /health
    http-check expect status 200
    cookie SERVERID insert indirect nocache   # Cookie 会话保持
    server web1 192.168.1.10:80 check inter 2s fall 3 rise 5 weight 1 cookie web1
    server web2 192.168.1.11:80 check inter 2s fall 3 rise 5 weight 1 cookie web2

backend api_servers
    mode http
    balance roundrobin
    option httpchk GET /api/health
    http-check expect status 200
    server api1 192.168.1.20:8080 check
    server api2 192.168.1.21:8080 check

backend static_servers
    mode http
    balance roundrobin
    server static1 192.168.1.30:80 check
    server static2 192.168.1.31:80 check

backend ws_servers
    mode http
    balance source          # Source IP 哈希,保证 WebSocket 粘性
    server ws1 192.168.1.40:8080 check
    server ws2 192.168.1.41:8080 check

# ============ 监控面板 ============
listen stats
    bind *:9000
    stats enable
    stats uri /haproxy
    stats auth admin:password123
    stats refresh 5s

七层关键特性说明:

  • acl is_api path_beg /api:匹配以 /api 开头的请求路径
  • use_backend ... if ...:根据 ACL 规则转发
  • option httpchk GET /health:HTTP 健康检查,请求 /health 接口
  • http-check expect status 200:期望返回 200 状态码
  • cookie SERVERID insert indirect nocache:自动插入 Cookie 实现会话保持
  • balance source:基于源 IP 哈希,同一客户端始终转发到同一后端

四、负载均衡算法对比

算法配置指令适用场景优缺点
轮询balance roundrobin后端性能均衡的 Web 服务简单均匀,不考虑后端负载
最少连接balance leastconn长连接场景(数据库/WebSocket)动态适应负载,有额外计算开销
Source IP 哈希balance source需要会话保持的无状态服务同一客户端固定后端,负载可能不均
URI 哈希balance uriCDN/缓存场景提高缓存命中率
一致性哈希balance uri + hash-type consistent后端动态扩缩容后端变动时影响最小

五、HAProxy + Keepalived 高可用配置

Keepalived 通过 VRRP 协议在主备节点之间漂移虚拟 IP(VIP),实现 HAProxy 的高可用,避免单点故障。

1.架构拓扑
            Client
               │
        VIP: 192.168.1.100
               │
    ┌──────────┴──────────┐
    │                     │
HAProxy Master       HAProxy Backup
 192.168.1.11        192.168.1.12
    │                     │
    └──────────┬──────────┘
               │
         Backend Servers
2.环境准备
节点角色主机名IP 地址说明
Masterlb01192.168.1.11主负载均衡器
Backuplb02192.168.1.12备负载均衡器
VIP192.168.1.100漂移虚拟 IP

两台节点均需安装 HAProxy 和 Keepalived:

yum install -y haproxy keepalived    # CentOS/RHEL
# apt install -y haproxy keepalived  # Debian/Ubuntu
3.系统参数配置(两台节点都执行)
# 开启 IP 转发
sed -i 's/#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/' /etc/sysctl.conf

# 允许绑定非本地 IP(VIP)
echo "net.ipv4.ip_nonlocal_bind = 1" >> /etc/sysctl.conf

sysctl -p
4.HAProxy 配置(两台节点相同)
global
    log /dev/log local0
    maxconn 4000
    daemon

defaults
    log     global
    mode    http
    option  httplog
    retries 3
    timeout connect 5000ms
    timeout client  50000ms
    timeout server  50000ms

frontend http_front
    bind *:80
    default_backend http_back

backend http_back
    balance roundrobin
    option httpchk GET /
    server web1 192.168.1.20:80 check inter 2s fall 3 rise 5
    server web2 192.168.1.21:80 check inter 2s fall 3 rise 5

listen stats
    bind *:9000
    stats enable
    stats uri /haproxy
    stats auth admin:password123

将配置同步到两台节点:

scp /etc/haproxy/haproxy.cfg lb02:/etc/haproxy/
5.Keepalived 配置

Master 节点(lb01) /etc/keepalived/keepalived.conf

global_defs {
    router_id lb01
}

# HAProxy 进程检测脚本
vrrp_script chk_haproxy {
    script "/usr/bin/killall -0 haproxy"
    interval 2
    weight 2
}

vrrp_instance VI_1 {
    state MASTER
    interface eth0                   # 根据实际网卡名修改
    virtual_router_id 51             # 主备必须相同
    priority 100                     # 主节点优先级 > 备节点
    advert_int 1

    authentication {
        auth_type PASS
        auth_pass 123456             # 主备必须相同
    }

    virtual_ipaddress {
        192.168.1.100/24             # VIP 地址
    }

    track_script {
        chk_haproxy                  # 关联健康检查脚本
    }
}

Backup 节点(lb02) /etc/keepalived/keepalived.conf

global_defs {
    router_id lb02
}

vrrp_script chk_haproxy {
    script "/usr/bin/killall -0 haproxy"
    interval 2
    weight 2
}

vrrp_instance VI_1 {
    state BACKUP
    interface eth0
    virtual_router_id 51             # 与 Master 相同
    priority 90                      # 低于 Master 的 100
    advert_int 1

    authentication {
        auth_type PASS
        auth_pass 123456             # 与 Master 相同
    }

    virtual_ipaddress {
        192.168.1.100/24
    }

    track_script {
        chk_haproxy
    }
}
6.启动与验证
# 检查 HAProxy 配置语法
haproxy -c -f /etc/haproxy/haproxy.cfg

# 两台节点分别启动服务
systemctl enable haproxy keepalived --now

# 在 Master 上验证 VIP 绑定
ip addr show eth0
# 应看到 192.168.1.100 已绑定

# 模拟故障:停止 Master 的 HAProxy
systemctl stop haproxy
# 等待几秒后,在 Backup 上检查 VIP 是否漂移过来
ip addr show eth0

# 恢复后 VIP 应自动漂回 Master
systemctl start haproxy
工作原理
  1. Master 节点持有 VIP,所有客户端流量通过 VIP 进入 Master 的 HAProxy
  2. Keepalived 每 2 秒执行 killall -0 haproxy 检测 HAProxy 进程
  3. 若 Master 的 HAProxy 宕机或 Master 整机故障,VRRP 协议触发 VIP 漂移
  4. Backup 节点自动接管 VIP,客户端无感知切换
  5. Master 恢复后,VIP 自动漂回(因 Master 优先级更高)

六、配置验证与排错

# 检查 HAProxy 配置语法
haproxy -c -f /etc/haproxy/haproxy.cfg

# 平滑重载配置(不中断现有连接)
systemctl reload haproxy

# 查看实时日志
tail -f /var/log/haproxy.log

# 测试不同路径转发
curl -v http://192.168.1.100/api/test
curl -v http://192.168.1.100/static/image.png

# 查看 VIP 绑定情况
ip addr show | grep 192.168.1.100
# 前台运行(调试模式,输出详细连接和请求信息)
haproxy -d -f /etc/haproxy/haproxy.cfg

# 前台运行但不进入后台(方便 Ctrl+C 停止)
haproxy -db -f /etc/haproxy/haproxy.cfg

# 实时查看日志
tail -f /var/log/haproxy.log

# 过滤错误日志
tail -f /var/log/haproxy.log | grep -i error

常见注意事项:

  • ACL 规则按顺序匹配,前面的优先级高,注意规则顺序
  • 路径匹配默认大小写敏感,/api/API 不同
  • 四层模式下无法使用 httpchk,只能用 TCP 连接检测
  • 七层模式下后端服务器看到的源 IP 是 HAProxy 的 IP,需通过 X-Forwarded-For 头传递真实客户端 IP
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值