DEBUG.WIKI
ZgoCloud:多地区部署,按需选节点;日本、美国、香港、德国
V.PS:让项目靠近用户,亚太、欧洲、北美 KVM VPS
晚安云;香港 CN2 ¥15/月

解决 Prometheus 报错 Target down context deadline exceeded 抓取超时

分析 Prometheus 抓取应用端点报 Target down context deadline exceeded 根因,详解 scrape_timeout 调优与慢指标排查步骤。

问题现象

在 Prometheus Web 控制台的 Targets 页面中,部分目标实例状态显示为红色 DOWN,并在 Error 列显示:

Get "http://10.244.2.15:8080/metrics": context deadline exceeded

或者伴随错误:Scrape timeout of 10s exceeded。监控面板中该实例的很多关键图表变成虚线断崖。

触发根因

  1. 目标 /metrics 接口内部执行严重卡顿:应用暴露监控指标时,每次抓取都实时遍历了超大规模的内存结构或同步查询了数据库,生成数十万行文本导致耗时超过了默认抓取超时(默认 10 秒)。
  2. Prometheus 配置的 scrape_timeout 设定过小:抓取耗时本身由于网络链路长需要 15 秒,而配置被硬性截断。
  3. 指标基数爆炸(Cardinality Explosion):在 Metric Label 中塞入了动态 UUID、用户 ID 等随机值,导致 /metrics 页面体积膨胀至数十兆。

诊断排查步骤

  1. 手动在 Prometheus 节点上 curl 目标监控地址并测量耗时:
time curl -s "http://10.244.2.15:8080/metrics" | wc -l

查看返回的总行数以及耗时秒数。

解决步骤与操作命令

步骤一:调优 prometheus.yml 中的 scrape_timeout(应急缓解)

注意:scrape_timeout 必须小于等于 scrape_interval:

scrape_configs:
  - job_name: "slow-app"
    scrape_interval: 30s
    scrape_timeout: 25s
    static_configs:
      - targets: ["10.244.2.15:8080"]

重载配置:

curl -X POST http://localhost:9090/-/reload

步骤二:清理业务指标中的高基数 Label(根治方案)

检查指标输出中是否存在包含动态变量的 Label,例如:

# 错误做法:在 Label 中放每次不同的 request_id
http_requests_total{method="GET", request_id="uuid-1234-abcd"} 1

在应用程序代码中移除高基数 Label,仅保留有限枚举值(如状态码、路由模板)。

步骤三:验证抓取状态恢复

在 Prometheus 控制台刷新 Targets 页面,目标状态恢复为绿色 UP,指标连续无丢包。