Skip to content

Prometheus 指标监控

HAProxy 内置 Prometheus 格式指标导出功能,可与 Prometheus + Grafana 配合实现可视化监控。

启用 Prometheus 指标

haproxy
frontend stats
    bind *:8404
    bind *:443 ssl crt /etc/ssl/certs/stats.pem
    stats enable
    stats uri /metrics
    stats auth admin:password
    # 启用 Prometheus 格式
    stats prometheus

Prometheus 配置

yaml
# /etc/prometheus/prometheus.yml
scrape_configs:
  - job_name: haproxy
    static_configs:
      - targets: [haproxy.example.com:8404]
    metrics_path: /metrics
    scheme: https

关键指标说明

吞吐量指标

指标名说明
haproxy_frontend_bytes_in_total前端入站字节总数
haproxy_frontend_bytes_out_total前端出站字节总数
haproxy_frontend_requests_total前端请求总数
haproxy_backend_bytes_in_total后端入站字节总数
haproxy_backend_bytes_out_total后端出站字节总数

健康状态指标

指标名说明
haproxy_backend_up后端服务器健康状态 (1=up, 0=down)
haproxy_server_up单个服务器健康状态

性能指标

指标名说明
haproxy_frontend_session_rate前端每秒会话数
haproxy_backend_queue_size后端队列大小
haproxy_backend_connect_time_avg后端连接平均耗时
haproxy_backend_response_time_avg后端响应平均耗时

错误指标

指标名说明
haproxy_frontend_requests_errors_total前端请求错误数
haproxy_backend_response_errors_total后端响应错误数
haproxy_backend_retries_total后端重试次数
haproxy_backend_queue_time_avg后端队列平均等待时间

Grafana Dashboard

推荐使用 HAProxy 官方 Dashboard (ID: 367),包含以下面板:

  • 请求率与带宽利用率
  • 响应时间分布 (P50/P95/P99)
  • 后端服务器健康状态
  • 错误率与 4xx/5xx 分布
  • 会话并发数
  • 队列深度监控

自定义指标采集

haproxy
frontend http_front
    bind *:80
    bind *:443 ssl crt /etc/ssl/certs/
    
    # 记录请求数到 Prometheus
    http-request track-sc0 var(req.counter) -1
    
    default_backend web_backend

告警规则示例

yaml
groups:
  - name: haproxy_alerts
    rules:
      - alert: HAProxyBackendDown
        expr: haproxy_backend_up == 0
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: HAProxy backend {{ $labels.backend }} is down

      - alert: HAProxyHighErrorRate
        expr: rate(haproxy_frontend_requests_errors_total[5m]) > 0.01
        for: 2m
        labels:
          severity: warning