You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求提供HAProxy负载均衡器配置示例

请求提供HAProxy负载均衡器配置示例

没问题!我给你一个基础且实用的HAProxy负载均衡配置示例,覆盖HTTP场景的核心功能,你可以根据自己的服务器环境调整参数。

首先,这是一个完整的haproxy.cfg配置文件示例,每个部分我都加了注释方便理解:

# 全局配置:设置HAProxy的基础运行参数
global
    log /dev/log    local0          # 主日志输出到syslog的local0
    log /dev/log    local1 notice   # 次要日志输出到local1,级别为notice
    chroot /var/lib/haproxy         # 切换到安全目录,提升安全性
    stats socket /run/haproxy/admin.sock mode 660 level admin expose-fd listeners
                                    # 管理套接字,用于HAProxy的命令行管理
    stats timeout 30s               # 管理套接字的超时时间
    user haproxy                    # 运行HAProxy的用户
    group haproxy                   # 运行HAProxy的用户组
    daemon                          # 以守护进程模式运行

    maxconn 4096                    # 全局最大并发连接数,根据服务器性能调整

# 默认配置:所有frontend和backend都会继承这些设置
defaults
    log     global                  # 继承全局的日志配置
    mode    http                    # 工作模式为HTTP(如果是TCP负载可以改成tcp)
    option  httplog                 # 记录详细的HTTP请求日志
    option  dontlognull             # 不记录空请求(比如健康检查的空请求)
    timeout connect 5000            # 与后端服务器建立连接的超时时间(5秒)
    timeout client  50000           # 客户端连接的超时时间(50秒)
    timeout server  50000           # 后端服务器响应的超时时间(50秒)
    # 自定义错误页面,HAProxy默认会提供这些文件,你也可以自己修改内容
    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

# 前端监听:处理客户端的HTTP请求
frontend http_front
    bind *:80                       # 监听服务器的80端口,接收所有客户端请求
    default_backend http_back       # 将所有请求转发到名为http_back的后端服务器池

# 后端服务器池:定义要负载均衡的后端Web服务器
backend http_back
    balance roundrobin              # 负载均衡算法:轮询(默认),还可以用leastconn(最少连接)等
    # 后端服务器列表,check表示HAProxy会定期检测服务器的健康状态
    server web1 192.168.1.10:80 check
    server web2 192.168.1.11:80 check
    server web3 192.168.1.12:80 check backup  # backup表示备用服务器,只有当主服务器都故障时才启用

# 可选:HAProxy统计页面,方便监控负载情况和服务器健康状态
frontend stats_front
    bind *:8080                     # 监听8080端口用于访问统计页面
    stats enable                    # 启用统计功能
    stats uri /haproxy-stats        # 统计页面的访问路径
    stats auth admin:yourpassword   # 访问统计页面的用户名和密码,记得改成自己的!

一些实用提示:

  • 修改配置后,记得用haproxy -f /etc/haproxy/haproxy.cfg -c检查配置语法是否正确
  • 重启HAProxy生效:sudo systemctl restart haproxy
  • 查看HAProxy日志:tail -f /var/log/haproxy.log,方便排查问题
  • 如果需要HTTPS负载均衡,可以在frontend的bind语句后添加SSL证书,比如bind *:443 ssl crt /path/to/your/cert.pem

备注:内容来源于stack exchange,提问作者Super22

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.17 10:08:09