Prometheus 监控 APISIX 全栈实战:云原生 API 网关的透明化可观测性

在这里插入图片描述


Apache APISIX 作为云原生 API 网关的佼佼者,凭借其动态路由、插件热插拔和高性能支撑着无数微服务集群的流量入口。它的 请求吞吐量上游健康状态响应延迟分布etcd 连接可靠性 以及 插件执行效率,直接决定了业务 API 的可用性与用户体验。从 APISIX 2.0 版本开始,内置的 prometheus 插件 就可将核心指标以 Prometheus 标准格式暴露,无需额外部署 Exporter。本文将带你从启用插件、配置抓取,到解读关键指标、搭建 Grafana 大屏和落地告警规则,彻底透视 APISIX 网关的每一个细节。


1. 为什么选择 APISIX 原生 Prometheus 插件?

  • 零侵入:插件内置,通过 Admin API 或声明式配置即可全局启用,无需重启。
  • 指标丰富:涵盖 HTTP 请求、连接数、带宽、上游状态、etcd 健康、插件调用统计等。
  • 高性能:基于内置的 prometheus 插件采集,对数据平面转发性能影响微乎其微。
  • 多协议支持:同时监控 HTTP 和 gRPC 流量。
  • 生态兼容:完美对接 Prometheus Operator、Grafana 社区仪表盘。

2. 启用 Prometheus 插件

2.1 全局启用(推荐)

通过 APISIX Admin API(默认 http://127.0.0.1:9180/apisix/admin)全局启用,使所有服务和路由的指标统一收集。

curl http://127.0.0.1:9180/apisix/admin/global_rules/1 -X PUT \
  -H "X-API-KEY: edd1c9f034335f136f87ad84b625c8f1" \
  -d '{
    "plugins": {
      "prometheus": {
        "prefer_name": true
      }
    }
  }'

参数 prefer_name 设为 true 时,指标标签中会使用路由和服务的名称(而非 ID),更易读。

2.2 在特定路由上启用

如果只需监控特定接口,可针对单个路由启用:

curl http://127.0.0.1:9180/apisix/admin/routes/1 -X PATCH \
  -H "X-API-KEY: ..." \
  -d '{
    "plugins": {
      "prometheus": {}
    }
  }'
2.3 验证端点

APISIX 默认在 数据平面端口 9091 上暴露 /apisix/prometheus/metrics(APISIX 2.7+ 开始)。在配置文件中确认 plugin_attr.prometheusexport_addr

# conf/config.yaml
plugin_attr:
  prometheus:
    export_addr:
      ip: "0.0.0.0"
      port: 9091

重启 APISIX 后,访问:

curl http://localhost:9091/apisix/prometheus/metrics

你将看到 apisix_http_requests_totalapisix_bandwidthapisix_etcd_modify_index 等指标。

注意:早期版本可能直接在 127.0.0.1:9091/metrics 或通过数据面端口提供,具体以版本为准。本文以 3.x 版本默认路径 /apisix/prometheus/metrics 为准。


3. 配置 Prometheus 抓取

3.1 静态配置
scrape_configs:
  - job_name: 'apisix'
    scrape_interval: 15s
    metrics_path: '/apisix/prometheus/metrics'
    static_configs:
      - targets: ['apisix-node1:9091', 'apisix-node2:9091']
        labels:
          cluster: 'prod'
          component: 'gateway'
3.2 Kubernetes 环境自动发现

如果 APISIX 部署在 K8s 中,使用 PodMonitor:

apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata:
  name: apisix
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: apisix
  podMetricsEndpoints:
  - port: prometheus
    path: /apisix/prometheus/metrics
    interval: 15s

需确保 APISIX Pod 暴露了名为 prometheus 的容器端口(对应 9091)。


4. 核心监控指标与 PromQL

APISIX 的 Prometheus 插件暴露的指标以 apisix_ 为前缀,标签包括 routeserviceconsumernodestatus 等。

4.1 HTTP 请求与状态码
指标含义
apisix_http_requests_totalHTTP 请求总数(Counter),按 routeserviceconsumerstatus 分组
apisix_http_status各状态码的请求数(与上类似,视版本可能合并)

PromQL 示例:

  • 整体 QPSsum(rate(apisix_http_requests_total[1m]))
  • 5xx 错误率sum(rate(apisix_http_requests_total{status=~"5.."}[5m])) / sum(rate(apisix_http_requests_total[5m]))
  • 某个路由的 QPSrate(apisix_http_requests_total{route="my-route"}[1m])
4.2 延迟
指标含义
apisix_http_latency (Histogram)APISIX 处理延迟(从接收到请求到转发给上游的时间)
apisix_upstream_latency (Histogram)上游服务响应时间

PromQL:

  • APISIX 处理延迟 P95histogram_quantile(0.95, rate(apisix_http_latency_bucket[5m]))
  • 上游延迟 P99histogram_quantile(0.99, rate(apisix_upstream_latency_bucket[5m]))
4.3 带宽
指标含义
apisix_bandwidth (Counter)入口和出口流量字节数,标签 typeingressegress

PromQL:

  • 入口流量(字节/秒)rate(apisix_bandwidth{type="ingress"}[1m])
  • 出口流量rate(apisix_bandwidth{type="egress"}[1m])
4.4 连接数
指标含义
apisix_nginx_http_current_connections当前 HTTP 连接数(包含 reading、writing、waiting)

类似 Nginx 连接状态。告警: apisix_nginx_http_current_connections{state="writing"} > 10000

4.5 上游健康与状态
指标含义
apisix_upstream_status上游健康检查状态(1=健康,0=不健康),按 upstream 标签
apisix_node_info节点信息(主机名、版本等)

告警:上游不健康apisix_upstream_status{upstream="backend-api"} == 0

4.6 etcd 连接与同步
指标含义
apisix_etcd_modify_indexetcd 修改索引,反映配置变更频率
apisix_etcd_reachableetcd 是否可达(1=连通,0=断开)

PromQL:

  • etcd 断连apisix_etcd_reachable == 0(立即告警)
  • 配置变更速率rate(apisix_etcd_modify_index[5m])
4.7 插件调用统计
指标含义
apisix_plugin_metrics特定插件(如 limit-countprometheus 本身)的执行计数和延迟

可据此分析限流、认证等插件的性能影响。


5. Grafana 仪表盘推荐

  • APISIX Official Dashboard:Dashboard ID 11719(Apache APISIX 社区官方仪表盘),完美适配 APISIX 2.x/3.x 的 Prometheus 指标,涵盖 QPS、延迟、带宽、上游状态、etcd 健康等。
  • APISIX Ingress Controller:若在 Kubernetes 中使用,可导入 ID 14403
  • 自定义业务视图:基于 routeservice 标签创建 QPS 排行、错误率热力、延迟分位数面板。

导入后选择数据源,通过 clusterinstance 变量区分不同 APISIX 集群。


6. 告警规则实战

groups:
  - name: apisix_alerts
    rules:
      - alert: APISIXNodeDown
        expr: up{job="apisix"} == 0
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: "APISIX 节点 {{ $labels.instance }} 指标端点不可达"

      - alert: APISIXEtcdDisconnected
        expr: apisix_etcd_reachable == 0
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: "APISIX 与 etcd 失去连接,配置可能无法生效"

      - alert: APISIXHigh5xxRate
        expr: sum(rate(apisix_http_requests_total{status=~"5.."}[5m])) by (instance)
              / sum(rate(apisix_http_requests_total[5m])) by (instance) > 0.01
        for: 5m
        labels:
          severity: critical
        annotations:
          summary: "APISIX 节点 {{ $labels.instance }} 5xx 错误率超过 1%"

      - alert: APISIXUpstreamUnhealthy
        expr: apisix_upstream_status == 0
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "上游服务 {{ $labels.upstream }} 健康检查失败"

      - alert: APISIXHighUpstreamLatency
        expr: histogram_quantile(0.99, rate(apisix_upstream_latency_bucket[5m])) > 2
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "上游服务 P99 延迟超过 2 秒"

      - alert: APISIXHighConnections
        expr: apisix_nginx_http_current_connections{state="writing"} > 10000
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "APISIX 正在写响应的连接数超过 10000,可能过载"

      - alert: APISIXBandwidthSaturation
        expr: rate(apisix_bandwidth{type="ingress"}[5m]) * 8 / 1e9 > 0.8
        for: 10m
        labels:
          severity: warning
        annotations:
          summary: "入口带宽使用率接近物理网卡上限"

根据实际硬件和流量调整阈值。


7. 进阶:多节点、安全与自定义指标

7.1 监控多个 APISIX 节点

每个节点独立暴露指标端点,Prometheus 中使用文件服务发现或 Kubernetes Pod 注解自动添加。使用标签 instancenode 区分。Grafana 中可通过变量切换或聚合。

7.2 安全加固
  • 指标端口保护:9091 端口仅监听内网 IP (export_addr 设为 127.0.0.1 或内网 IP),或使用防火墙限制。
  • 认证:APISIX 指标端点本身无鉴权,建议通过 Nginx/Caddy 反向代理添加 Basic Auth,然后 Prometheus 配置 basic_auth
  • Admin API 隔离:永远不要将 Admin API (9180) 暴露到公网。
7.3 自定义业务指标

APISIX 支持通过 serverless 插件或自定义 Lua 插件向 prometheus 模块注册新指标。例如,统计特定 API 的调用次数:

local prometheus = require("apisix.plugins.prometheus")
prometheus.define_metric("custom_api_calls", "counter", "API calls", {"api_name"})
-- 在逻辑中
prometheus.inc("custom_api_calls", {"login"})

这些自定义指标会同样暴露在 /apisix/prometheus/metrics 端点。

7.4 结合日志与追踪

当告警触发时,可联动 APISIX 的访问日志(写入 Kafka/Loki)和 SkyWalking/Zipkin 追踪,快速定位错误原因。Prometheus 负责发现问题,日志和追踪负责诊断问题。


8. 总结

通过 APISIX 内置的 Prometheus 插件,云原生 API 网关的每一个请求、每一字节带宽、每一次上游健康检查和 etcd 同步状态都转化为可查询、可告警的时序数据。结合 Grafana 仪表盘和 Alertmanager 的及时通知,你可以在网关 5xx 错误率攀升、上游服务宕机或 etcd 断连时第一时间响应。将 APISIX 的可观测性无缝纳入全栈监控体系,意味着从网关到后端微服务,整个流量生命周期的透明化已经完成。部署它,让 APISIX 不仅是高性能的流量入口,更是完全可观测的云原生网关基石。

更多推荐