13.2.5 初始验证与基本配置检查

本节聚焦安装完成后的初始验证与基本配置检查,确保 HAProxy 可正常启动、配置语法无误、运行状态可观测,为后续负载均衡与高可用配置打下稳定基础。

原理草图:启动路径与请求转发#

文章图片

1. 二进制与版本校验(含命令解释)#

# 查看版本与基础信息
haproxy -v
# 预期:显示版本号与构建日期

# 查看编译选项与启用模块
haproxy -vv
# 重点关注:USE_OPENSSL、USE_ZLIB、USE_PROMEX、USE_LUA 等

排错要点:
- 若缺少 SSL/Lua/Prometheus 模块,说明编译选项未启用或包版本功能有限,需要更换发行版包或重新编译。

2. 配置文件位置与权限确认#

# 常见配置路径
ls -l /etc/haproxy/haproxy.cfg

# 查看运行用户(以 systemd 为例)
systemctl cat haproxy | sed -n '1,120p'

# 检查日志目录(示例)
ls -ld /var/log/haproxy

排错要点:
- 配置文件或日志目录权限不足会导致启动失败或日志缺失。
- 配置文件中包含不可见字符会导致语法失败,建议使用 cat -A 检查。

3. 配置语法检查(不启动服务)#

# 仅做语法检查,不启动服务
haproxy -c -f /etc/haproxy/haproxy.cfg

# 若需详细输出
haproxy -c -V -f /etc/haproxy/haproxy.cfg

常见错误示例与修复:

[ALERT]  Invalid line: "use_backend app if app_acl"
# 修复:确保 app_acl 已定义且拼写一致

4. 最小可用配置示例(可直接运行)#

目标:验证端口监听、转发、健康检查与 stats 页面。

文件: /etc/haproxy/haproxy.cfg

global
    log 127.0.0.1 local0
    maxconn 2000
    user haproxy
    group haproxy

defaults
    mode http
    log global
    option httplog
    timeout connect 5s
    timeout client  30s
    timeout server  30s

frontend fe_http
    bind *:8080
    default_backend be_app

backend be_app
    balance roundrobin
    option httpchk GET /health
    server s1 127.0.0.1:8081 check
    server s2 127.0.0.1:8082 check

listen stats
    bind *:8404
    stats enable
    stats uri /stats
    stats refresh 5s

启动两个简单后端(示例)

# 终端1:启动后端1
python3 -m http.server 8081 &
# 终端2:启动后端2
python3 -m http.server 8082 &

语法检查并启动

haproxy -c -f /etc/haproxy/haproxy.cfg
systemctl restart haproxy

验证转发与统计页

curl -I http://127.0.0.1:8080/
# 预期:HTTP/1.0 200 OK 或 301/404(来自 python http.server)

curl -I http://127.0.0.1:8404/stats
# 预期:HTTP/1.1 200 OK

5. 服务状态与端口检查#

systemctl status haproxy -l

# 查看监听端口
ss -lntp | grep haproxy

# 查看进程
ps -ef | grep [h]aproxy

排错要点:
- 端口冲突:ss -lntp | grep 8080
- 进程未启动:检查 /var/log/haproxy.log 或系统日志。

6. 日志与运行时状态检查#

启用 rsyslog(示例)

# /etc/rsyslog.d/49-haproxy.conf
local0.*    /var/log/haproxy.log
systemctl restart rsyslog
tail -f /var/log/haproxy.log

常见日志问题:
- Connection refused:后端未启动或端口不通
- Health check failedoption httpchk 路径返回非 2xx

7. 初始问题快速排查清单(含命令)#

  • 端口被占用
ss -lntp | grep 8080
  • SELinux 拦截(CentOS/RHEL)
getenforce
setenforce 0   # 临时
  • 防火墙阻断
firewall-cmd --list-ports
firewall-cmd --add-port=8080/tcp --permanent && firewall-cmd --reload
  • 后端不可达
curl -I http://127.0.0.1:8081/health

8. 练习:从零完成一次最小验证#

  1. 使用上述最小配置文件启动 HAProxy。
  2. 启动两个 Python HTTP 服务作为后端。
  3. 通过 curl 验证 8080 转发与 8404 stats 页面。
  4. 停掉一个后端,观察 stats 页面状态变化,并在日志中找到健康检查失败记录。
  5. 修改 balanceleastconn,再次验证请求分配变化(可多次访问观察)。