HAProxy 教程

1. 核心概念

HAProxy(High Availability Proxy)是一款功能强大的开源负载均衡器和反向代理服务器,专为高可用性、高性能和可靠性而设计。它可以用于 TCP 和 HTTP 应用,提供了丰富的负载均衡算法、健康检查、会话保持等功能。

1.1 基本概念

  • 负载均衡:将请求分发到多个后端服务器,提高系统的可用性和性能。
  • 反向代理:接收客户端请求,转发到后端服务器,然后将响应返回给客户端。
  • 前端(Frontend):定义如何接收客户端请求。
  • 后端(Backend):定义如何处理和转发请求到后端服务器。
  • 服务器(Server):后端服务器的定义。
  • 健康检查:定期检查后端服务器的健康状态,自动排除故障服务器。
  • 会话保持:将来自同一客户端的请求转发到同一后端服务器,保持会话一致性。
  • ACL:访问控制列表,用于根据请求属性执行不同的操作。
  • SSL/TLS 终端:处理 HTTPS 请求,终止 SSL/TLS 连接。

1.2 工作原理

  • 事件驱动架构:使用事件驱动模型,高效处理并发连接。
  • 多层设计:前端接收请求,根据配置转发到后端,后端将请求分发到服务器。
  • 健康检查:定期检查后端服务器的健康状态,自动排除故障服务器。
  • 负载均衡算法:根据配置的算法(如轮询、最少连接等)分发请求。
  • 会话管理:支持多种会话保持方式,确保会话一致性。

2. 安装配置

2.1 安装 HAProxy

2.1.1 Ubuntu/Debian

# 更新软件包列表
apt update

# 安装 HAProxy
apt install haproxy

# 查看 HAProxy 版本
haproxy -v

2.1.2 CentOS/RHEL

# 安装 EPEL 仓库
yum install epel-release

# 安装 HAProxy
yum install haproxy

# 查看 HAProxy 版本
haproxy -v

2.1.3 从源码编译

# 下载 HAProxy
wget https://www.haproxy.org/download/2.4/src/haproxy-2.4.20.tar.gz

# 解压
tar -xzvf haproxy-2.4.20.tar.gz

# 进入目录
cd haproxy-2.4.20

# 编译
make TARGET=linux-glibc

# 安装
make install

2.2 基本配置

HAProxy 的主配置文件通常位于 /etc/haproxy/haproxy.cfg

基本配置示例

# 全局配置
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
    # 最大连接数
    maxconn 2000

# 默认配置
defaults
    log     global
    mode    http
    option  httplog
    option  dontlognull
    timeout connect 5000
    timeout client  50000
    timeout server  50000
    errorfile 400 /etc/haproxy/errors/400.http
    errorfile 403 /etc/haproxy/errors/403.http
    errorfile 408 /etc/haproxy/errors/408.http
    errorfile 500 /etc/haproxy/errors/500.http
    errorfile 502 /etc/haproxy/errors/502.http
    errorfile 503 /etc/haproxy/errors/503.http
    errorfile 504 /etc/haproxy/errors/504.http

# 统计页面
listen stats
    bind *:8080
    stats enable
    stats uri /stats
    stats realm HAProxy\ Statistics
    stats auth admin:password
    stats refresh 10s

# 前端配置
frontend http_front
    bind *:80
    default_backend http_back

# 后端配置
backend http_back
    balance roundrobin
    server server1 192.168.1.10:80 check
    server server2 192.168.1.11:80 check
    server server3 192.168.1.12:80 check

2.3 配置检查和重载

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

# 重载配置文件
systemctl reload haproxy

# 启动 HAProxy
systemctl start haproxy

# 启用 HAProxy 开机自启
systemctl enable haproxy

# 查看 HAProxy 状态
systemctl status haproxy

3. 基本使用

3.1 HTTP 负载均衡

配置示例

# 前端配置
frontend http_front
    bind *:80
    default_backend http_back

# 后端配置
backend http_back
    # 负载均衡算法
    balance roundrobin
    # 后端服务器
    server server1 192.168.1.10:80 check
    server server2 192.168.1.11:80 check
    server server3 192.168.1.12:80 check
    # 健康检查
    option httpchk GET /health
    http-check expect status 200
    # 健康检查间隔
    default-server inter 3s fall 3 rise 2

3.2 HTTPS 终端

配置示例

# 前端配置
frontend https_front
    bind *:443 ssl crt /etc/haproxy/certs/example.com.pem
    default_backend http_back

# 后端配置
backend http_back
    balance roundrobin
    server server1 192.168.1.10:80 check
    server server2 192.168.1.11:80 check

3.3 TCP 负载均衡

配置示例

# 前端配置
frontend tcp_front
    bind *:3306
    mode tcp
    default_backend mysql_back

# 后端配置
backend mysql_back
    mode tcp
    balance roundrobin
    server mysql1 192.168.1.10:3306 check
    server mysql2 192.168.1.11:3306 check

3.4 会话保持

配置示例

# 后端配置
backend http_back
    balance roundrobin
    # 基于 cookie 的会话保持
    cookie SERVERID insert indirect nocache
    server server1 192.168.1.10:80 check cookie server1
    server server2 192.168.1.11:80 check cookie server2
    
    # 或者基于 IP 的会话保持
    # balance source
    # hash-type consistent

4. 高级功能

4.1 ACL 配置

配置示例

# 前端配置
frontend http_front
    bind *:80
    
    # ACL 定义
    acl url_static path_beg /static /images /css
    acl url_api path_beg /api
    acl host_blog hdr(host) -i blog.example.com
    acl host_api hdr(host) -i api.example.com
    
    # ACL 应用
    use_backend static_back if url_static
    use_backend api_back if url_api
    use_backend blog_back if host_blog
    use_backend api_back if host_api
    default_backend http_back

# 后端配置
backend static_back
    balance roundrobin
    server server1 192.168.1.10:80 check

backend api_back
    balance roundrobin
    server server1 192.168.1.11:8080 check

backend blog_back
    balance roundrobin
    server server1 192.168.1.12:80 check

backend http_back
    balance roundrobin
    server server1 192.168.1.13:80 check

4.2 健康检查

配置示例

# 后端配置
backend http_back
    balance roundrobin
    
    # HTTP 健康检查
    option httpchk GET /health
    http-check expect status 200
    
    # TCP 健康检查
    # option tcp-check
    # tcp-check connect
    # tcp-check send GET\ /health\ HTTP/1.0\r\n\r\n
    # 健康检查参数
    default-server inter 3s fall 3 rise 2 timeout 10s
    
    # 后端服务器
    server server1 192.168.1.10:80 check
    server server2 192.168.1.11:80 check
    server server3 192.168.1.12:80 check backup

4.3 速率限制

配置示例

# 前端配置
frontend http_front
    bind *:80
    
    # 速率限制
    stick-table type ip size 100k expire 1m store http_req_rate(10s)
    tcp-request connection track-sc1 src
    tcp-request connection reject if { sc_http_req_rate(1) gt 10 }
    
    default_backend http_back

# 后端配置
backend http_back
    balance roundrobin
    server server1 192.168.1.10:80 check
    server server2 192.168.1.11:80 check

4.4 重写和重定向

配置示例

# 前端配置
frontend http_front
    bind *:80
    
    # 重定向到 HTTPS
    redirect scheme https code 301 if !{ ssl_fc }
    
    # 重写 URL
    http-request set-path /new-path/%[path,regsub(^/old-path/,/)] if { path_beg /old-path/ }
    
    default_backend http_back

# 后端配置
backend http_back
    balance roundrobin
    server server1 192.168.1.10:80 check
    server server2 192.168.1.11:80 check

4.5 压缩

配置示例

# 后端配置
backend http_back
    balance roundrobin
    
    # 启用压缩
    compression algo gzip
    compression type text/html text/plain text/css application/javascript application/json
    
    server server1 192.168.1.10:80 check
    server server2 192.168.1.11:80 check

5. 最佳实践

5.1 配置最佳实践

  • 使用模块化配置:将不同功能的配置分离到不同的文件中,提高可读性和可维护性。
  • 使用变量:合理使用变量,减少重复配置。
  • 设置合理的超时:根据应用的特性,设置合理的连接超时、客户端超时、服务器超时等。
  • 启用健康检查:配置适当的健康检查,及时发现和排除故障服务器。
  • 使用会话保持:对于需要会话一致性的应用,使用适当的会话保持方式。
  • 配置统计页面:启用统计页面,便于监控和故障排查。

5.2 性能优化

  • 调整最大连接数:根据服务器硬件和应用特性,设置合理的最大连接数。
  • 选择合适的负载均衡算法:根据应用的特性,选择合适的负载均衡算法。
  • 优化健康检查:合理设置健康检查的间隔和参数,避免对后端服务器造成过大压力。
  • 启用连接复用:启用连接复用,减少连接建立的开销。
  • 使用 HTTP/2:启用 HTTP/2,提高传输效率。
  • 优化 SSL/TLS:使用现代的 SSL/TLS 配置,启用会话复用。

5.3 高可用配置

  • 使用主备架构:部署多个 HAProxy 实例,使用 Keepalived 实现高可用。
  • 配置故障转移:使用 Keepalived 或其他工具实现 HAProxy 实例的故障转移。
  • 分散负载:在多个 HAProxy 实例之间分散负载,提高系统的可用性和性能。
  • 定期备份:定期备份 HAProxy 配置文件,以便在故障时快速恢复。

5.4 安全最佳实践

  • 更新 HAProxy:及时更新 HAProxy 到最新版本,修复安全漏洞。
  • 限制访问:使用 ACL 限制对敏感路径的访问。
  • 配置 SSL/TLS:使用强密码套件,启用 HTTP/2 和 HSTS。
  • 隐藏版本信息:在配置中隐藏 HAProxy 版本信息。
  • 使用防火墙:配置防火墙,限制对 HAProxy 端口的访问。
  • 定期检查日志:定期检查 HAProxy 日志,及时发现异常情况。

6. 实用应用案例

6.1 Web 应用负载均衡

场景:为 Web 应用提供负载均衡,提高可用性和性能。

配置

# 全局配置
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
    maxconn 4000

# 默认配置
defaults
    log     global
    mode    http
    option  httplog
    option  dontlognull
    option  http-server-close
    option  forwardfor   except 127.0.0.0/8
    option  redispatch
    retries 3
    timeout connect 5000
    timeout client  50000
    timeout server  50000

# 统计页面
listen stats
    bind *:8080
    stats enable
    stats uri /stats
    stats realm HAProxy\ Statistics
    stats auth admin:password
    stats refresh 10s

# 前端配置
frontend web_front
    bind *:80
    bind *:443 ssl crt /etc/haproxy/certs/example.com.pem
    http-request redirect scheme https if !{ ssl_fc }
    default_backend web_back

# 后端配置
backend web_back
    balance roundrobin
    option httpchk GET /health
    http-check expect status 200
    default-server inter 3s fall 3 rise 2 timeout 10s
    server web1 192.168.1.10:8080 check cookie web1
    server web2 192.168.1.11:8080 check cookie web2
    server web3 192.168.1.12:8080 check cookie web3 backup
    cookie SERVERID insert indirect nocache

6.2 API 网关

场景:作为 API 网关,路由请求到不同的后端服务,提供认证、限流等功能。

配置

# 全局配置
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
    maxconn 4000

# 默认配置
defaults
    log     global
    mode    http
    option  httplog
    option  dontlognull
    option  http-server-close
    option  forwardfor   except 127.0.0.0/8
    option  redispatch
    retries 3
    timeout connect 5000
    timeout client  50000
    timeout server  50000

# 统计页面
listen stats
    bind *:8080
    stats enable
    stats uri /stats
    stats realm HAProxy\ Statistics
    stats auth admin:password
    stats refresh 10s

# 前端配置
frontend api_front
    bind *:80
    bind *:443 ssl crt /etc/haproxy/certs/api.example.com.pem
    http-request redirect scheme https if !{ ssl_fc }
    
    # ACL 定义
    acl path_auth path_beg /auth
    acl path_users path_beg /users
    acl path_products path_beg /products
    acl path_orders path_beg /orders
    
    # 速率限制
    stick-table type ip size 100k expire 1m store http_req_rate(10s)
    tcp-request connection track-sc1 src
    tcp-request connection reject if { sc_http_req_rate(1) gt 100 }
    
    # 路由规则
    use_backend auth_back if path_auth
    use_backend users_back if path_users
    use_backend products_back if path_products
    use_backend orders_back if path_orders
    default_backend default_back

# 后端配置
backend auth_back
    balance roundrobin
    option httpchk GET /health
    http-check expect status 200
    default-server inter 3s fall 3 rise 2 timeout 10s
    server auth1 192.168.1.10:9000 check

backend users_back
    balance roundrobin
    option httpchk GET /health
    http-check expect status 200
    default-server inter 3s fall 3 rise 2 timeout 10s
    server users1 192.168.1.11:9001 check

backend products_back
    balance roundrobin
    option httpchk GET /health
    http-check expect status 200
    default-server inter 3s fall 3 rise 2 timeout 10s
    server products1 192.168.1.12:9002 check

backend orders_back
    balance roundrobin
    option httpchk GET /health
    http-check expect status 200
    default-server inter 3s fall 3 rise 2 timeout 10s
    server orders1 192.168.1.13:9003 check

backend default_back
    http-request deny

6.3 数据库负载均衡

场景:为数据库集群提供负载均衡,提高可用性和性能。

配置

# 全局配置
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
    maxconn 4000

# 默认配置
defaults
    log     global
    mode    tcp
    option  tcplog
    option  dontlognull
    option  tcp-check
    retries 3
    timeout connect 5000
    timeout client  50000
    timeout server  50000

# 统计页面
listen stats
    bind *:8080
    stats enable
    stats uri /stats
    stats realm HAProxy\ Statistics
    stats auth admin:password
    stats refresh 10s

# MySQL 负载均衡
listen mysql
    bind *:3306
    mode tcp
    balance roundrobin
    option tcp-check
    tcp-check connect
    tcp-check send quit\ \r\n
    # 主服务器
    server mysql1 192.168.1.10:3306 check weight 100
    server mysql2 192.168.1.11:3306 check weight 50 backup

# PostgreSQL 负载均衡
listen postgres
    bind *:5432
    mode tcp
    balance roundrobin
    option tcp-check
    tcp-check connect
    tcp-check send QUIT\ \r\n
    server postgres1 192.168.1.12:5432 check
    server postgres2 192.168.1.13:5432 check
    server postgres3 192.168.1.14:5432 check

7. 总结

HAProxy 是一款功能强大、性能优秀的负载均衡器和反向代理服务器,广泛应用于各种场景,从简单的 Web 应用负载均衡到复杂的 API 网关。

通过本教程的学习,您应该已经掌握了 HAProxy 的核心概念、安装配置、基本使用、高级功能和最佳实践。在实际应用中,您可以根据具体的需求,灵活配置 HAProxy,以满足不同场景的要求。

7.1 核心优势

  • 高性能:事件驱动架构,高效处理并发连接。
  • 功能丰富:支持多种负载均衡算法、健康检查、会话保持、ACL 等功能。
  • 可靠性:经过多年的发展和验证,具有良好的可靠性和稳定性。
  • 灵活性:丰富的配置选项,可以满足各种需求。
  • 可扩展性:可以通过配置和模块扩展功能。
  • 开源免费:开源软件,免费使用。

7.2 应用前景

随着互联网的发展和应用规模的扩大,对负载均衡和反向代理的需求越来越高。HAProxy 作为一款成熟的负载均衡器,在以下场景中有着广泛的应用前景:

  • Web 应用负载均衡:为 Web 应用提供负载均衡,提高可用性和性能。
  • API 网关:作为 API 网关,路由请求到不同的后端服务,提供认证、限流等功能。
  • 数据库负载均衡:为数据库集群提供负载均衡,提高可用性和性能。
  • 微服务架构:在微服务架构中,作为服务间通信的代理,提供负载均衡和服务发现。
  • 云环境:在云环境中,作为应用的入口点,提供负载均衡和高可用。

通过不断学习和实践 HAProxy 的功能和最佳实践,您可以充分发挥 HAProxy 的优势,构建高性能、可靠、安全的负载均衡系统。

« 上一篇 Caddy 教程 下一篇 » Traefik 教程