13.3.2 默认区(defaults)与继承机制

默认区(defaults)与继承机制#

defaults 区为后续的 frontend/backend/listen 提供可继承的基线行为,减少重复配置并统一超时、日志、模式等关键策略。合理设计 defaults 可显著降低配置维护成本与误配置风险。

原理草图:继承与覆盖关系

文章图片

1. 继承规则与作用范围
- defaults 中的参数会被其后定义的 frontend、backend、listen 自动继承。
- 子段同名参数覆盖 defaults(就近优先)。
- 可定义多个 defaults 分组(如 http/tcp)以区分协议与策略。

2. 常用默认项与含义(示例释义)
- mode:协议模式,决定可用指令集(http/tcp)。
- log:日志输出与格式(通常配合 global 的日志设施)。
- option:行为开关(httplogdontlognullhttp-keep-alive 等)。
- timeout:连接与请求超时(connect/client/server/http-request)。
- retries:后端连接重试次数。
- maxconn:默认最大并发连接数。
- option forwardfor:HTTP 下添加 X-Forwarded-For

3. 完整可执行示例(含多 defaults 分组)
配置文件路径示例:/etc/haproxy/haproxy.cfg

global
    log /dev/log local0
    maxconn 50000
    user haproxy
    group haproxy
    daemon

defaults http
    mode http
    log global
    option httplog
    option dontlognull
    option http-keep-alive
    option forwardfor
    timeout connect 5s
    timeout client  30s
    timeout server  30s
    timeout http-request 10s
    retries 3
    maxconn 10000

defaults tcp
    mode tcp
    log global
    option tcplog
    timeout connect 5s
    timeout client  2m
    timeout server  2m
    retries 3
    maxconn 5000

frontend web_in
    bind *:80
    # 继承 defaults http
    default_backend web_pool

backend web_pool
    # 继承 defaults http
    server web1 10.0.0.11:8080 check
    server web2 10.0.0.12:8080 check

listen redis_tcp
    bind *:6379
    # 继承 defaults tcp
    server r1 10.0.0.21:6379 check

4. 继承与覆盖示例(覆盖长连接场景)

frontend ws_in
    bind *:8081
    # 继承 defaults http,但需要长连接
    timeout client 2m
    default_backend ws_pool

预期效果ws_in 的客户端空闲超时由 30s 覆盖为 2m,不影响其他前端。

5. 关键命令与解释(配置检查与生效)

# 语法检查(不启动)
haproxy -c -f /etc/haproxy/haproxy.cfg

# 重载配置(systemd)
systemctl reload haproxy

# 查看当前进程与监听端口
ss -lntp | grep haproxy
  • -c:仅做语法校验,避免错误配置导致服务中断。
  • reload:优雅重载,尽量不影响已有连接。

6. 排错清单(defaults 常见问题)
- 问题:HTTP 日志缺失或格式异常
排查:确认 defaults http 中启用 option httplog,且 log global 正确指向 global。
- 问题:WebSocket/长轮询频繁断开
排查:检查 defaults 的 timeout client/server 是否过小,必要时在对应 frontend 覆盖。
- 问题:TCP 服务被当作 HTTP
排查:确认对应 listen/backend 继承的是 defaults tcp,或显式设置 mode tcp

7. 练习
1. 为 HTTP 与 TCP 服务分别设计 defaults 分组,要求:
- HTTP 设置 timeout client 30s
- TCP 设置 timeout client 2m
- 两者日志格式不同。
2. 将 frontend web_intimeout client 覆盖为 60s,并验证语法通过。
3. 故意删除 defaults httpmode http,观察 haproxy -c 输出,记录错误提示并修复。