17.1.2 核心组件:Prometheus Server与TSDB
Prometheus Server 负责抓取、存储、查询与规则评估;TSDB 负责本地时序存储与检索。理解二者的协作与边界,是容量规划与故障定位的基础。
架构原理草图#
核心机制要点#
- 抓取器按
scrape_interval拉取目标指标并写入 WAL; - Head Block 持有最新样本,周期性压缩为 Block(默认 2h);
- 规则引擎周期性执行 recording/alerting 规则;
- 查询引擎扫描 Head + Blocks,基于索引与 chunks 加速检索;
- 高基数标签会导致索引膨胀与查询变慢。
安装与最小可运行示例#
以 Linux 服务器二进制部署为例:
# 1) 下载并解压
cd /opt
curl -LO https://github.com/prometheus/prometheus/releases/download/v2.50.0/prometheus-2.50.0.linux-amd64.tar.gz
tar xf prometheus-2.50.0.linux-amd64.tar.gz
ln -s /opt/prometheus-2.50.0.linux-amd64 /opt/prometheus
# 2) 创建数据目录
mkdir -p /data/prometheus
# 3) 最小配置
cat >/opt/prometheus/prometheus.yml <<'EOF'
global:
scrape_interval: 15s
evaluation_interval: 30s
scrape_configs:
- job_name: "prometheus"
static_configs:
- targets: ["127.0.0.1:9090"]
EOF
# 4) 启动 Prometheus Server
/opt/prometheus/prometheus \
--config.file=/opt/prometheus/prometheus.yml \
--storage.tsdb.path=/data/prometheus \
--storage.tsdb.retention.time=7d \
--web.listen-address="0.0.0.0:9090"
预期效果:
- 访问 http://<IP>:9090 Web UI;
- Status -> TSDB Status 可看到 Head/Blocks/WAL 状态。
TSDB 关键参数与命令解释#
/opt/prometheus/prometheus \
--storage.tsdb.path=/data/prometheus \ # TSDB 数据目录
--storage.tsdb.retention.time=15d \ # 数据保留时长
--storage.tsdb.retention.size=20GB \ # 保留上限(触发淘汰)
--storage.tsdb.wal-compression \ # WAL 压缩
--storage.tsdb.max-block-duration=2h \ # Block 最大时长
--storage.tsdb.min-block-duration=2h # Block 最小时长
建议只设置
retention.time或retention.size之一,避免维护复杂。
示例:查看 TSDB 状态与样本写入#
# 查看 TSDB 运行状态
curl -s http://127.0.0.1:9090/api/v1/status/tsdb | jq
# 查看 Prometheus 自身指标中的 WAL 大小与样本速率
curl -s http://127.0.0.1:9090/metrics | \
egrep 'prometheus_tsdb_wal_size_bytes|prometheus_tsdb_head_samples_appended_total'
故障排查速查#
1) 抓取失败(入口问题)
# 查看目标抓取状态
curl -s http://127.0.0.1:9090/api/v1/targets | jq '.data.activeTargets[]|{job: .labels.job, health: .health, lastError: .lastError}'
- 常见原因:网络不通、目标端口未开放、目标路径错误。
2) WAL 膨胀或磁盘暴涨
# 统计 WAL 目录占用
du -sh /data/prometheus/wal
- 常见原因:抓取速率过高、高基数标签;解决:降低抓取频率、清理标签、增加磁盘。
3) 查询变慢
# 查看查询超时/耗时
curl -s http://127.0.0.1:9090/metrics | egrep 'prometheus_engine_query_duration_seconds'
- 常见原因:查询跨度过大、标签维度过多;优化:增加 recording rules、减少高基数标签。
小练习#
1) 将 scrape_interval 从 15s 改为 5s,观察 prometheus_tsdb_head_samples_appended_total 增长速度变化。
2) 添加一个高基数标签(如 instance_id),比较 TSDB 索引大小变化:
# 模拟:在一个 exporter 中增加高基数标签(示意)
3) 将 retention.time 设置为 1d,观察旧 block 被清理的效果(/data/prometheus/ 目录变化)。