Files
wiki/监控/Prometheus/Prometheus-学习手册-01-入门与架构篇.md
2026-10-08 15:05:32 +08:00

81 KiB
Raw Permalink Blame History

Prometheus 知识学习手册 · 第 1 篇:入门与架构

基于 prometheus.io 官方文档 整理 文档版本:Prometheus v3.15.0(最新稳定版,2026-10 发布)| 抓取日期:2026-10-08 数据来源:prometheus/prometheus@v3.15.0、prometheus/alertmanager、prometheus/docs 官方仓库源文件(与官网 latest 内容一致)

全册结构(共 4 篇)

  • 第 1 篇:入门与架构 ← 本篇
  • 第 2 篇:PromQL 与查询
  • 第 3 篇:配置与运维
  • 第 4 篇:Alertmanager 与生态(告警、插桩、可视化、规范)

目录


第 1 章 概述

1.1 Prometheus 是什么

Prometheus 是一个开源的系统监控与告警工具箱(monitoring and alerting toolkit)。

  • 最初由 SoundCloud 构建,2012 年启动。
  • 2016 年作为继 Kubernetes 之后第二个托管项目加入 Cloud Native Computing Foundation(CNCF,cncf.io)。
  • 现为独立开源项目,独立于任何公司维护。
  • 它是 Kubernetes 唯一直接支持的系统监控方案,也是云原生生态的事实标准。

其数据本质是:以**时间序列数据(time series data)**采集并存储指标——即每条指标信息都带记录时的时间戳,并附带可选的键值对 labels。

💡 补充:Prometheus 的“复数”在官方 FAQ 中经研究确定为 Prometheis;记不住时可直接用 “Prometheus instances”。

引自:Overview | Frequently asked questions | Getting started with Prometheus

1.2 解决什么问题

要理解 Prometheus 解决什么问题,先理解 metrics(指标) 与 time series(时间序列)。

  • metrics:通俗意义上的数值测量。
  • time series:随时间变化的记录。

为什么需要它:不同应用关心的测量内容不同——

系统类型 典型关注指标
Web 服务器 请求耗时(request times)
数据库 CPU 使用率、活跃连接数、活跃查询数

以“Web 服务器变慢”为例:请求计数(request count)指标显示请求量变高,据此即可判断“变慢是因为请求量高”,并据此扩容服务器。

官方教程给出的指标定义自问法(非常实用):

“what all information will be important for me to debug if any issue occurs in my application?” (如果我的应用出了问题,哪些信息对调试重要?)

Prometheus 就是系统化地回答这个问题的工具:定义指标 → 暴露指标 → 抓取存储 → 查询告警。

引自:Overview | Getting started with Prometheus

1.3 核心特点

官方 Overview 列出的核心特性(Features)逐条如下:

# 特性 说明
1 多维数据模型(multi-dimensional data model) 时间序列由 metric name 与 key/value pairs(即 labels)标识
2 PromQL 灵活查询语言,用于充分利用该多维性
3 单节点自治 不依赖分布式存储,single server nodes are autonomous
4 Pull 模型采集 时间序列采集通过 HTTP 上的 pull model 完成
5 支持 Push 通过中间网关(push gateway)支持推送时间序列
6 服务发现 targets 通过 service discovery 或静态配置(static configuration)发现
7 多种可视化 支持多种绘图(graphing)与仪表盘(dashboarding)模式

可靠性定位:Prometheus 的设计目标是可靠性——它是故障时快速诊断的首选系统。每个 Prometheus server 都是独立的,不依赖网络存储或其他远程服务,因此即使基础设施的其他部分损坏,Prometheus 仍可依赖,而且无需搭建大量基础设施。

💡 补充(来自官方 FAQ):Prometheus 的取舍是最看重“可靠地把告警送达人类”(reliably delivering alerts to humans)。这一点在第 1.4 节“何时不该用”中会看到其反面影响。

引自:Overview

1.4 适用场景:何时该用、何时不该用

何时该用(When does it fit)

  • 适合记录任何纯数值的时间序列。
  • 既适配以机器为中心的监控(machine-centric monitoring),也适配高度动态的面向服务架构(highly dynamic service-oriented architectures)。
  • 在微服务场景下,多维数据采集与多维查询是显著优势。
  • 需要高可靠性、快速故障诊断的场景——Prometheus server 独立自治,不依赖网络存储或远程服务。

何时不该用(When does it not fit)

  • Prometheus 重可靠性而非 100% 准确性。
  • 若需要 100% 准确(典型例子:按请求计费 per-request billing),不适合——因为采集的数据可能不够详尽、不够完整。
  • 正确做法:另用一个系统专门做计费数据采集,Prometheus 负责其余监控。

选择决策速查表

你的需求 是否适合 Prometheus 说明
记录纯数值时间序列 ✅ 适合 核心用例
机器/主机监控 ✅ 适合 配合 Node Exporter
高度动态的云原生 / 微服务 ✅ 适合 多维模型 + 服务发现
需要可靠的告警送达 ✅ 适合 设计目标即“可靠地把告警送达人类”
按请求计费(per-request billing) ❌ 不适合 需 100% 准确,另建专用系统
日志/事件采集 ❌ 不适合 见 FAQ:应改用 Grafana Loki 或 OpenSearch
长期历史数据(超单节点容量) ⚠️ 需外部方案 借助 remote write 到长期存储系统(如 Thanos 等)

引自:Overview | Frequently asked questions

1.5 竞品对比

本节基于官方 Comparison to alternatives 页面整理,对比 Prometheus 与 Graphite、InfluxDB、OpenTSDB、Nagios、Sensu 等系统。

1.5.1 总览对比表

维度 Prometheus Graphite InfluxDB OpenTSDB Nagios Sensu
类型 完整监控与告警系统 被动时序数据库 + 查询 + 绘图 开源时序数据库(有商用集群版) 基于 Hadoop/HBase 的分布式时序库 基于脚本 exit code 的告警系统 开源可观测性 pipeline
主动抓取 ✅ 内置 ❌ 交给外部组件 ❌ 需外部 ❌ 需外部 主动 check(脚本) ✅ 事件驱动
查询语言 PromQL(强,支持聚合/切片/预测/join) 有查询语言(弱于 PromQL) 有(弱于 PromQL) API 仅支持简单聚合与数学运算 ❌ 无查询语言 有限
多维标签 ✅ labels(key-value,显式) ❌ 点分 metric name 隐式编码 ✅ 称 tags(另有 fields) ✅ 称 tags(同 Prometheus labels) ❌ 无 labels 概念 ✅ labels/annotations
告警/通知 ✅ Alertmanager(分组、去重、静默、限流) ❌ 交给外部 需搭配 Kapacitor ❌ ✅ 但无分组/路由/去重 ✅ 事件处理强
存储 本地 TSDB(block + WAL),接受任意间隔样本 Whisper(RRD 风格,要求固定间隔,过期覆盖) 时间分片 LSM tree + WAL Hadoop/HBase 之上 除当前状态外无存储 嵌入式 etcd 或外部 PostgreSQL
水平扩展 单节点自治,超容量需按边界显式分片 集群方案更成熟适合长历史 商用版分布式集群,易水平扩展 易水平扩展(需运维 Hadoop/HBase) 单 server,文件配置 组件可集群
开源模式 完全开源、独立项目 开源 open-core(单一商业公司) 开源 开源 open-core(单一商业公司)

1.5.2 vs. Graphite

  • Scope(范围):Graphite 侧重做被动的时序数据库 + 查询语言 + 绘图,其他关注点交给外部组件。Prometheus 是全套监控与趋势系统,内置主动抓取、存储、查询、绘图、基于时序数据的告警;它知道“世界应是什么样”(哪些端点应存在、哪些时序模式意味着异常)并主动找故障。

  • Data model(数据模型):Graphite 存的是命名时序的数值样本。Graphite 用点分隔的 metric name 隐式编码维度;Prometheus 则用显式的 key-value pairs(labels)附加于 metric name,便于按标签过滤、分组、匹配。Graphite 搭配 StatsD 时常只存所有实例的聚合数据,不保留 instance 维度,无法下钻到具体问题实例。

    编码示例对比:

    # Graphite/StatsD 编码(仅一个聚合值,丢失实例维度)
    stats.api-server.tracks.post.500 -> 93
    
    # Prometheus 编码(假设三个 api-server 实例,可下钻到实例)
    api_server_http_requests_total{method="POST",handler="/tracks",status="500",instance="<sample1>"} -> 34
    api_server_http_requests_total{method="POST",handler="/tracks",status="500",instance="<sample2>"} -> 28
    api_server_http_requests_total{method="POST",handler="/tracks",status="500",instance="<sample3>"} -> 31
    
  • Storage(存储):Graphite 用 Whisper 格式存本地磁盘,RRD 风格,要求样本按固定间隔到达;每个时序单独一个文件,过时后新样本覆盖旧样本。Prometheus 本地 TSDB 用内存 head(由 write-ahead log 保护)保存近期样本,再以基于时间的 block 目录持久化(含 chunks 目录、index 与 metadata),接受任意间隔的样本;保留期可配置,适合大量短生命周期、频繁变化的时序。

  • Summary:Prometheus 数据模型与查询语言更丰富、更易运行集成;若需要可长期持有历史数据的集群方案,Graphite 可能更合适。

1.5.3 vs. InfluxDB

  • InfluxDB 是开源时序数据库,有商用扩展/集群选项;其项目发布晚于 Prometheus 开发开始近一年。公平比较需连同 Kapacitor 一起看(两者合计对应 Prometheus + Alertmanager 的问题域)。

  • 功能对应关系:

    InfluxDB 侧能力 Prometheus 侧对应
    InfluxDB continuous queries Prometheus recording rules
    Kapacitor 全部范围 Prometheus recording rules + alerting rules + Alertmanager 通知功能

    Prometheus 查询语言更强;Alertmanager 另有分组、去重、静默。

  • Data model / storage:InfluxDB 的 labels 称 tags,另有二级 labels 称 fields(用途更受限);支持最高纳秒分辨率时间戳,类型 float64、int64、bool、string。Prometheus 支持 float64(字符串支持有限)与毫秒分辨率时间戳。InfluxDB 用按时间分片的 log-structured merge tree + write ahead log,更适合事件日志;Prometheus 基于 block 的本地 TSDB 针对监控时序优化。

  • Architecture:Prometheus server 各自独立运行,核心功能(抓取、规则处理、告警)仅依赖本地存储;开源版 InfluxDB 类似。商用 InfluxDB 按设计是分布式存储集群(存储与查询由多节点处理),更易水平扩展但需从一开始管理分布式存储复杂性;Prometheus 更易运行,但超单节点容量后需按 scalability 边界(产品、服务、数据中心等)显式分片。独立 server(可并行冗余运行)带来更好可靠性与故障隔离。

  • Kapacitor:开源版无内置 rules/alerting/notifications 的分布式/冗余选项,可由用户手动分片扩展;Influx 提供 Enterprise Kapacitor 支持 HA/冗余告警。Prometheus 与 Alertmanager 则通过运行冗余 Prometheus 副本 + Alertmanager 高可用模式,提供完全开源的冗余选项。

  • Summary:

    • 相似处:都用 labels(InfluxDB 称 tags)支持多维指标;都用基本相同的数据压缩算法;都有广泛集成(包括互相);都有扩展钩子。
    • InfluxDB 更优:做事件日志时;商用版聚类更适合长期数据存储;副本间最终一致视图。
    • Prometheus 更优:主要做 metrics 时;查询语言、告警、通知更强;绘图与告警的可用性与 uptime 更高。
    • 维护模式:InfluxDB 由单一商业公司按 open-core 模式维护(闭源聚类、托管、支持等增值功能);Prometheus 是完全开源独立项目。

1.5.4 vs. OpenTSDB

  • 基于 Hadoop 与 HBase 的分布式时序数据库。Scope 差异同 Graphite 处。
  • Data model:与 Prometheus 几乎相同——时序由任意 key-value pairs 标识(OpenTSDB tags = Prometheus labels)。某 metric 的全部数据存于一起,限制 metric 基数(cardinality)。差异:Prometheus 允许 label value 使用任意字符,OpenTSDB 更受限;OpenTSDB 缺少完整查询语言,API 仅支持简单聚合与数学运算。
  • Storage:OpenTSDB 存储实现在 Hadoop/HBase 之上,易水平扩展,但需从头接受运行 Hadoop/HBase 集群的复杂性;Prometheus 初期更易运行,但超过单节点容量后需显式分片。
  • Summary:Prometheus 查询语言丰富、可处理更高基数、是完整监控系统的一部分;若已运行 Hadoop 且更看重长期存储,OpenTSDB 是好选择。

1.5.5 vs. Nagios

  • 起源于 1990 年代(名为 NetSaint)。
  • Scope:主要基于脚本 exit codes 告警,称为 "checks";可静默单个告警,但无分组、路由或去重。插件生态丰富(如将 perfData 管道到 Graphite 等时序库,或用 NRPE 在远程机器执行 checks)。
  • Data model:以 host 为基础,每 host 可含一个或多个 services,每 service 执行一个 check;无 labels 概念,无查询语言。
  • Storage:除当前 check 状态外无存储;有插件可存储数据用于可视化。
  • Architecture:Nagios server 独立;所有 check 配置通过文件。
  • Summary:适合小型/静态系统的基础监控(blackbox probing 足够时)。若做 whitebox monitoring 或环境动态/基于云,选 Prometheus。

1.5.6 vs. Sensu

  • 开源监控与可观测性 pipeline,有商用发行版提供扩展性功能,可复用现有 Nagios 插件。
  • Scope:是 observability pipeline,侧重把可观测性数据作为 Events 流处理与告警,提供可扩展框架用于 event filtering、aggregation、transformation、processing(含向其他系统发告警、把事件存到第三方系统)。其事件处理能力范围类似 Prometheus alerting rules + Alertmanager。
  • Data model:Sensu Events 以结构化格式表示服务健康与/或 metrics,由 entity 名(如 server、云实例、container 或 service)、event name 及可选 key-value metadata(称 "labels" 或 "annotations")标识。Event payload 可含一个或多个 metric points,以 JSON 对象表示,含 name、tags(key/value pairs)、timestamp、value(总是 float)。
  • Storage:当前与近期事件状态信息及实时 inventory 存于嵌入式数据库(etcd)或外部 RDBMS(PostgreSQL)。
  • Architecture:所有组件可集群,以实现高可用与更高事件处理吞吐。
  • Summary:
    • 共同点:都有可扩展的动态云环境发现机制;都支持通过 labels/annotations 收集多维指标;都有广泛集成;Sensu 原生支持从所有 Prometheus exporters 收集指标;都可转发可观测性数据到第三方平台。
    • Sensu 更优:收集处理混合可观测性数据(metrics 与/或 events);整合多监控工具且需支持 metrics 与 Nagios 风格插件/check 脚本;事件处理平台更强。
    • Prometheus 更优:主要收集与评估 metrics;监控同构 Kubernetes 基础设施(若 100% 工作负载在 K8s,Prometheus 的 K8s 集成更好);查询语言更强且内置历史数据分析支持。
    • 维护模式:Sensu 由单一商业公司按 open-core 模式维护;Prometheus 是完全开源独立项目。

引自:Comparison to alternatives | Frequently asked questions


第 2 章 快速上手

2.1 环境要求

  • Prometheus 使用 Go 编写,只需对应操作系统的编译二进制即可运行。
  • 运行只需两样东西:二进制 + 配置文件(配置文件使用 YAML 格式)。
  • 官方为多数 Prometheus 组件提供预编译二进制(precompiled binaries)。

💡 补充(工程经验,非官方原文):Prometheus 官方只发布 Linux/macOS/Windows 的可执行文件,本身是静态编译的单一二进制,无需额外运行时依赖。生产环境建议运行在 Linux 服务器上,并为其预留独立的数据盘(TSDB 数据目录 --storage.tsdb.path,默认 ./data)。

引自:Installation | Getting started with Prometheus | Getting started

2.2 下载与安装

官方 Installation 页面给出的安装方式逐条如下。

2.2.1 方式一:预编译二进制

  • 为多数官方 Prometheus 组件提供预编译二进制,版本列表见 https://prometheus.io/download。

  • 下载后解包:

    tar xvfz prometheus-*.tar.gz
    cd prometheus-*
    
  • 服务器为单一二进制 prometheus(Windows 下为 prometheus.exe)。用 --help 查看所有选项:

    ./prometheus --help
    usage: prometheus [<flags>]
    
    The Prometheus monitoring server
    
    . . .
    

💡 补充(来自官方 Tutorials 教程):也可下载后把二进制目录加入系统 PATH,之后即可直接以 prometheus --config.file=prometheus.yml 启动。

2.2.2 方式二:从源码构建

  • 见各仓库的 Makefile targets(例如 prometheus/prometheus 仓库)。

2.2.3 方式三:Docker

  • 所有 Prometheus 服务提供 Docker 镜像,位于 Quay.io 或 Docker Hub。

  • 最简启动(以示例配置启动并暴露 9090 端口):

    docker run -p 9090:9090 prom/prometheus
    
  • 镜像使用 volume 存储实际 metrics。生产部署强烈建议使用 named volume,以便升级时管理数据。

  • 命令行参数注意:镜像以若干默认命令行参数启动(可在 Dockerfile 中查看);若想追加参数,需自行重新加上原有参数,否则会被覆盖。

挂载配置示例(二选一):

# 只挂载单个配置文件
docker run -p 9090:9090 -v /path/to/prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus

# 挂载整个配置目录
docker run -p 9090:9090 -v /path/to/config:/etc/prometheus prom/prometheus

保存数据(持久化):数据存于容器内 /prometheus 目录,容器重启即清空;需设置持久化存储:

docker volume create prometheus-data
docker run -p 9090:9090 -v /path/to/prometheus.yml:/etc/prometheus/prometheus.yml -v prometheus-data:/prometheus prom/prometheus

自定义镜像(把配置烤入镜像):

FROM prom/prometheus
ADD prometheus.yml /etc/prometheus/
docker build -t my-prometheus .
docker run -p 9090:9090 my-prometheus
  • 更高级选项:启动时用工具动态渲染配置,或由守护进程定期更新。

2.2.4 方式四:配置管理系统(第三方贡献)

工具 项目地址
Ansible prometheus-community/ansible
Chef rayrod2030/chef-prometheus
Puppet puppet/prometheus
SaltStack saltstack-formulas/prometheus-formula

引自:Installation

2.3 5 分钟跑通

这一节把“下载 → 写配置 → 启动 → 首次查询 → 用 UI”串成一条最小可用路径,素材来自官方 First steps with Prometheus。

2.3.1 配置文件详解

Prometheus 配置为 YAML,下载包自带示例配置 prometheus.yml,注释以 # 前缀。

global:
  scrape_interval:     15s
  evaluation_interval: 15s

rule_files:
  # - "first.rules"
  # - "second.rules"

scrape_configs:
  - job_name: prometheus
    static_configs:
      - targets: ['localhost:9090']

配置由三个配置块组成:

配置块 作用 关键字段说明
global 全局默认 scrape_interval 控制抓取频率(本例 15 秒,可按 target 单独覆盖);evaluation_interval 控制规则求值频率,规则用于创建新时间序列与生成告警
rule_files 规则文件位置 指定要加载的规则文件位置;示例中暂无规则
scrape_configs 监控哪些资源 默认单 job 名为 prometheus,抓取 Prometheus server 自身暴露的时间序列;含单个静态配置 target:localhost 的 9090 端口

2.3.2 启动

./prometheus --config.file=prometheus.yml

启动后:

2.3.3 首次查询(表达式浏览器)

访问 http://localhost:9090/query,选择 "Table" 标签页。

示例指标 promhttp_metric_handler_requests_total(Prometheus 自身已处理的 /metrics 请求总数):

promhttp_metric_handler_requests_total

返回若干时间序列(各带最新值):metric name 相同但 labels 不同,labels 用于标识不同请求状态。

只查看 HTTP 200:

promhttp_metric_handler_requests_total{code="200"}

统计返回的时间序列数量:

count(promhttp_metric_handler_requests_total)

2.3.4 UI 使用(绘图界面)

2.3.5 监控其他 target

引自:First steps with Prometheus

2.4 官方 Hello World 教程完整步骤

本节按官方 Getting started(核心文档中的 “Hello World” 式教程)的完整流程展开:下载并在本地运行 Prometheus,配置其抓取自身与一个示例应用,再通过查询、规则、图表使用采集到的时序数据。

2.4.1 步骤 1:下载并解包

tar xvfz prometheus-*.tar.gz
cd prometheus-*

2.4.2 步骤 2:编写自监控配置

保存为 prometheus.yml:

global:
  scrape_interval:     15s # By default, scrape targets every 15 seconds.
  external_labels:
    monitor: 'codelab-monitor'
scrape_configs:
  - job_name: 'prometheus'
    scrape_interval: 5s
    static_configs:
      - targets: ['localhost:9090']

要点:global.scrape_interval 全局 15s;job 级 scrape_interval: 5s 覆盖全局值;external_labels 添加 monitor: 'codelab-monitor'。

2.4.3 步骤 3:启动

./prometheus --config.file=prometheus.yml

2.4.4 步骤 4:用表达式浏览器探索数据

访问 http://localhost:9090/query 并选择 "Graph" 标签页:

prometheus_target_interval_length_seconds
prometheus_target_interval_length_seconds{quantile="0.99"}
count(prometheus_target_interval_length_seconds)

其中 prometheus_target_interval_length_seconds 表示 target 抓取之间的实际耗时。

绘图示例:

rate(prometheus_tsdb_head_chunks_created_total[1m])

2.4.5 步骤 5:启动示例 target(Node Exporter)

tar -xzvf node_exporter-*.*.tar.gz
cd node_exporter-*.*
./node_exporter --web.listen-address 127.0.0.1:8080
./node_exporter --web.listen-address 127.0.0.1:8081
./node_exporter --web.listen-address 127.0.0.1:8082

2.4.6 步骤 6:将多个端点归入一个 job 并分组

将三个端点归入一个名为 node 的 job,前两个为 production、第三个为 canary:

scrape_configs:
  - job_name:       'node'
    scrape_interval: 5s
    static_configs:
      - targets: ['localhost:8080', 'localhost:8081']
        labels:
          group: 'production'
      - targets: ['localhost:8082']
        labels:
          group: 'canary'

在 http://localhost:9090/targets 或 Status → Target health 查看:三个端点状态应为 UP;若为 DOWN,检查对应端口上 Node Exporter 是否仍在运行。

示例返回序列:

node_cpu_seconds_total{cpu="0",group="production",instance="localhost:8080",job="node",mode="idle"}

在查询选项菜单(表达式输入框右侧三点按钮)→ Explore metrics 可浏览全部 metric name。

2.4.7 步骤 7:定义 Recording rule

将表达式 avg by (job, instance, mode) (rate(node_cpu_seconds_total[5m])) 预录为 job_instance_mode:node_cpu_seconds:avg_rate5m,保存为 prometheus.rules.yml:

groups:
- name: cpu-node
  rules:
  - record: job_instance_mode:node_cpu_seconds:avg_rate5m
    expr: avg by (job, instance, mode) (rate(node_cpu_seconds_total[5m]))

在 prometheus.yml 中:

  • 加入 rule_files: ['prometheus.rules.yml'];
  • 在 global 中加入 evaluation_interval: 15s(Evaluate rules every 15 seconds)。

2.4.8 步骤 8:重载配置与优雅关闭

重载配置(无需重启):发送 SIGHUP 信号。

kill -s SIGHUP <PID>

优雅关闭(推荐用信号/中断):

  • Linux 上发送 SIGTERM 或 SIGINT:

    kill -s <SIGNAL> <PID>
    
  • 或在控制终端按中断字符(默认 ^C)。

💡 补充(来自官方 FAQ):除 SIGHUP 外,也可向 /-/reload 端点发 HTTP POST 重载配置;各组件会尽量优雅处理失败的变更。

引自:Getting started | Frequently asked questions

2.4.9 Tutorials 版快速上手(含 node_exporter)

官方 Tutorials → Getting started with Prometheus 给出了更精简的版本:

第一步:只抓取自身。

global:
  scrape_interval: 15s

scrape_configs:
  - job_name: prometheus
    static_configs:
      - targets: ["localhost:9090"]

含义:scrape_interval 定义抓取频率;scrape_configs 含 job 名称与抓取目标。Prometheus 默认监听 9090 端口,故把 localhost:9090 加入 targets。

启动:

prometheus --config.file=prometheus.yml

此时 Prometheus 已运行并每 15s 抓取自身指标。

第二步:接入 node exporter。 先运行 exporter(机器指标 exporter,下载:https://prometheus.io/download/#node_exporter):

./node_exporter

再加入 scrape_configs:

global:
  scrape_interval: 15s

scrape_configs:
  - job_name: prometheus
    static_configs:
      - targets: ["localhost:9090"]
  - job_name: node_exporter
    static_configs:
      - targets: ["localhost:9100"]

抓取原理示例:以 web server 为例,用 Prometheus client library 添加 instrumentation 代码暴露指标;配置 Prometheus 从该 web server(监听 IP 端口 7500)按固定间隔(如每分钟)抓取:

Time Stamp Request Count (metric)
11:00:00 0
11:01:00 1
11:02:00 3
  • 11:00:00 首次抓取 request count 存为 0;
  • 11:01:00 处理 1 个请求,count 增至 1;
  • 11:02:00 再处理 2 个请求,count = 1 + 2 = 3。
  • 抓取频率由用户控制。
  • 备注:该表仅用于理解,Prometheus 并非以此确切格式存储值。

查询 API:Prometheus 提供 API 查询已抓取并存储的指标,用于查询指标、创建 dashboard/chart 等,使用 PromQL。

引自:Getting started with Prometheus

2.5 验证安装成功

检查项 方法 预期结果
进程已启动 访问 http://localhost:9090 能看到自身状态页
metrics 端点正常 访问 http://localhost:9090/metrics 返回文本格式指标(约启动 30 秒后有数据)
目标健康 http://localhost:9090/targets 或 Status → Target health prometheus target 状态为 UP
查询可用 http://localhost:9090/query 选 Table,执行 promhttp_metric_handler_requests_total 返回带不同 labels 的多条时间序列
规则已加载(配置规则后) http://localhost:9090/rules 能看到已定义的 record/alert 规则
告警可查(接入 Alertmanager 后) http://localhost:9090/alerts 能看到告警及状态

引自:First steps with Prometheus | Getting started

2.6 常见启动问题

💡 补充:以下内容为基于官方文档各处的工程实践提示,官方未单列“常见启动问题”章节,故以排错清单形式给出。

现象 可能原因 排查方向
状态页打不开 端口被占用 / 监听地址不对 检查 --web.listen-address(默认 0.0.0.0:9090);用 lsof -i :9090 查占用
target 状态 DOWN 被监控进程未运行 / 端口错误 官方指引:检查对应端口上 exporter(如 Node Exporter)是否仍在运行
配置文件报错无法启动 YAML 语法错误 / 字段拼写错误 用 promtool check config prometheus.yml 校验(见官方 promtool 文档)
启动后查询无数据 抓取尚未完成 官方说明:约需 30 秒才开始采集到自身 HTTP 指标端点数据
Docker 中数据丢失 数据存于容器内 /prometheus,容器重启即清空 使用 named volume:-v prometheus-data:/prometheus
Docker 中自定义参数不生效 镜像有默认命令行参数,追加参数会覆盖默认参数 需自行重新加上原有默认参数
配置改了不生效 未重载 发送 SIGHUP,或向 /-/reload 发 HTTP POST
关闭时数据/状态异常 直接 kill 未优雅退出 使用 SIGTERM/SIGINT 优雅关闭

引自:First steps with Prometheus | Installation | Getting started | Frequently asked questions


第 3 章 核心概念

3.1 数据模型详解

3.1.1 时间序列(Time Series)

  • Prometheus 把所有数据都存储为 time series(时间序列):属于同一 metric 且同一组 labeled dimensions 的、带时间戳的值的流。
  • 除已存储的序列外,Prometheus 还可能因查询生成临时派生序列。
  • 每条时间序列由 metric name 和可选的键值对 labels 唯一标识。

3.1.2 样本(Sample)

  • 每个 sample 由两部分组成:
    组成 说明
    值 一个 float64 值,或一个 native histogram 值
    时间戳 毫秒精度时间戳

💡 补充(来自官方 FAQ 的 Implementation 一节):之所以样本值都是 64 位浮点,是为了简化设计。IEEE 754 双精度二进制浮点格式支持整数精度至 2^53。原生 64 位整数仅在需要 2^53 以上、2^63 以下整数精度时才有帮助。原则上可实现不同样本值类型(含大整数,超过 64 位),但目前非优先。即便 counter 每秒递增一百万次,也需超过 285 年才会遇到精度问题。

3.1.3 Metric name(指标名)

命名规则:

  • SHOULD 描述被测量系统的通用特征(如 http_requests_total 表示收到的 HTTP 请求总数);
  • MAY 使用任意 UTF-8 字符;
  • SHOULD 匹配正则 [a-zA-Z_:][a-zA-Z0-9_:]*,否则在 PromQL 中使用时需加引号;
  • 冒号 : 保留给用户自定义 recording rules,exporters 或直接插桩 SHOULD NOT 使用。

3.1.4 Metric labels(指标标签)

  • 用于捕获同一 metric name 的不同实例(如所有用 POST 方法访问 /api/tracks 的 HTTP 请求),这种模型称为 "dimensional data model"(维度化数据模型)。
  • 任何 label 值变化(含增删 label)都会创建新的时间序列。
  • 命名规则:
    对象 规则
    label name MAY 任意 UTF-8;以 __(双下划线)开头 MUST 保留给 Prometheus 内部使用;SHOULD 匹配 [a-zA-Z_][a-zA-Z0-9_]*
    label value MAY 含任意 UTF-8
    空 label value 等价于该 label 不存在

3.1.5 命名规则速查表

对象 SHOULD 匹配的正则 备注
metric name [a-zA-Z_:][a-zA-Z0-9_:]* : 保留给 recording rules;不匹配则 PromQL 中需加引号
label name [a-zA-Z_][a-zA-Z0-9_]* __ 前缀为 Prometheus 内部保留
label value 无字符集限制 可为任意 UTF-8;空值等于 label 不存在

3.1.6 UTF-8 说明(重要警示)

Warning

:metric/label name 的 UTF-8 支持在 Prometheus v3.0.0 才加入。生态(下游 PromQL 兼容项目、工具、第三方插桩、collectors)可能尚未跟进。为兼容性,建议沿用上文 SHOULD 字符集。

3.1.7 Notation(记法)

标准记法:

<metric name>{<label name>="<label value>", ...}

示例(与 OpenTSDB 记法相同):

api_http_requests_total{method="POST", handler="/messages"}

UTF-8 字符(超出推荐集)需加引号:

{"<metric name>", <label name>="<label value>", ...}

因 metric name 内部表示为特殊 label __name__,也可写作:

{__name__="<metric name>", <label name>="<label value>", ...}

引自:Data model | Frequently asked questions

3.2 四种指标类型

Prometheus 插桩库提供四种核心 metric type:Counter、Gauge、Histogram、Summary。

关键前提:除 native histogram 外,这些类型目前只在插桩库 API 与 exposition 协议中区分;Prometheus server 尚不使用类型信息,除 native histogram 外全部扁平化为浮点值 untyped time series。native histogram 则以特殊的复合 histogram sample 的时间序列被摄入。

3.2.1 四种类型对比总表

类型 语义 单调性 典型用途 常用 PromQL
Counter 累积型(cumulative)、单调递增计数器 只增,重启时可重置为 0 请求数、完成任务数、错误数 rate()、increase()
Gauge 可任意上下浮动的单个数值 可升可降 温度、当前内存占用、并发请求数、队列中事件数、集群 pod 数 max_over_time、min_over_time、avg_over_time
Histogram 按可配置 buckets 对观测值计数 + 观测值之和(本质是 bucketed counter) 累积 请求耗时(latency)、响应大小等分布 histogram_quantile()、histogram_fraction()、rate()
Summary 类似 histogram,另在滑动时间窗上计算可配置分位数 累积 请求时长、响应大小 直接读取 {quantile="φ"}

3.2.2 Counter(计数器)

  • 是什么:累积型(cumulative)metric,表示只增不减的单调递增计数器(monotonically increasing counter),值只能在重启时被重置为 0。

  • 怎么用:适合表示请求数、完成任务数、错误数。

  • 不该用在哪:不可用于可能下降的值(如当前运行进程数——应改用 gauge)。

  • 注意:rate() 函数仅适用于 counter 值。

  • 教程中的示例查询:

    go_gc_duration_seconds_count
    

    rate() 取某时间窗内指标历史,计算每秒增长速度:

    rate(go_gc_duration_seconds_count[5m])
    

3.2.3 Gauge(仪表盘)

  • 是什么:表示可任意上下浮动的单个数值。

  • 怎么用:用于温度、当前内存占用,或可升可降的“计数”如并发请求数。

  • 教程中的示例查询:

    go_memstats_heap_alloc_bytes
    

    可用 PromQL 函数(作用于 gauge 指标):max_over_time、min_over_time、avg_over_time。

3.2.4 Histogram(直方图)

是什么:按可配置的 buckets 对观测值计数,并提供所有观测值之和,本质是 bucketed counter。它也可表示分布的当前状态,此时称为 gauge histogram(例如 rate 函数作用于 counter histogram 的结果)。

版本分类:histogram 有两种版本——较新的 native histograms 与较旧的 classic histograms。

classic histogram 产生的序列(base name 为 <basename>):

序列 含义
<basename>_bucket{le="<upper inclusive bound>"} 观测 bucket 的累积计数器
<basename>_sum 所有观测值总和
<basename>_count 观测事件计数(等同于 <basename>_bucket{le="+Inf"})

native histogram 的优势:

  • 以 composite samples 暴露与摄入,每个 sample 表示观测的计数与总和,并带一组动态 bucket;
  • 更高效、分辨率更高;
  • 插桩时无需显式配置 bucket 边界;
  • 网络传输(如 remote write)具备原子性(classic histogram 因各组成序列独立传输可能部分传输);
  • 其 bucketing schema 保证总可互相聚合。

支持情况:当前支持 native histogram 的插桩库为 Go 和 Java,建议优先使用 native histogram。若只能用 classic,可配置 Prometheus 将其摄入为 Native Histograms with Custom Bucket boundaries(NHCB)——存储为相同 composite samples,但 bucket 布局与 classic 一致、分辨率与可聚合性受限。

分位数计算:用 histogram_quantile() 从 histogram(或 histogram 聚合)计算分位数,classic 与 native 均适用但语法略有不同;也可算 Apdex score。classic bucket 是累积的(每个 bucket 统计小于等于该 label 上界的所有观测);native histogram 可用 histogram_fraction() 计算落在给定边界内的观测比例,并用 trim operators 过滤波段。

教程中的分桶示例:以“观察处理 API 请求耗时”为例。不存储每个请求的时间,而是分桶存储。定义耗时 bucket:le 0.3、le 0.5、le 0.7、le 1、le 1.2。请求耗时计算后,被加到所有 bucket 边界高于该测量值的 bucket 计数中。

  • Request 1,端点 /ping 耗时 0.25 s:

    Bucket Count
    0 - 0.3 1
    0 - 0.5 1
    0 - 0.7 1
    0 - 1 1
    0 - 1.2 1
    0 - +Inf 1

    备注:+Inf bucket 是默认添加的。由于 histogram 是累积频率(cumulative frequency),所有大于该值的 bucket 计数都加 1。

  • Request 2,端点 /ping 耗时 0.4 s:

    Bucket Count
    0 - 0.3 1
    0 - 0.5 2
    0 - 0.7 2
    0 - 1 2
    0 - 1.2 2
    0 - +Inf 2

    因为 0.4 低于 0.5,所有直到该边界的 bucket 计数增加。

在 UI 中探索 histogram 指标:

prometheus_http_request_duration_seconds_bucket{handler="/graph"}

histogram_quantile() 计算分位数:

histogram_quantile(0.9,prometheus_http_request_duration_seconds_bucket{handler="/graph"})

图中显示第 90 百分位数为 0.09。计算最近 5m 的 histogram_quantile,使用 rate() 与时间窗:

histogram_quantile(0.9, rate(prometheus_http_request_duration_seconds_bucket{handler="/graph"}[5m]))

Note

:自 Prometheus v3.0 起,classic histogram 的 le label 值在摄入时按 OpenMetrics Canonical Numbers 格式归一化。

3.2.5 Summary(摘要)

  • 是什么:类似 histogram,采样观测值(通常是请求时长、响应大小),提供观测总数与所有观测值之和,并在滑动时间窗口上计算可配置的分位数。

  • 暴露的序列(base name 为 <basename>,在抓取时暴露多条序列):

    序列 含义
    <basename>{quantile="<φ>"} 流式 φ-quantiles(0 ≤ φ ≤ 1)
    <basename>_sum 总和
    <basename>_count 计数
  • 优缺点:是 histogram 的替代方案;更省资源(cheaper)但丢失更多数据。在应用层计算,因此无法聚合同一进程多个实例的指标。

  • 适用:指标 bucket 事先未知的场景;但强烈建议尽可能优先使用 histograms 而非 summaries。

Note

:自 Prometheus v3.0 起,quantile label 值在摄入时按 OpenMetrics Canonical Numbers 格式归一化。

3.2.6 类型选型决策指南

你要测量的东西 推荐类型 理由
请求数 / 错误数 / 完成任务数 Counter 只增不减,可配 rate() 看速率
当前进程数 / 并发数 / 温度 / 内存占用 Gauge 可升可降
请求耗时/响应大小的分布、需算分位数 Histogram(优先 native) 可跨实例聚合;native 无需预设桶、可原子传输
bucket 边界事先未知、且无需跨实例聚合 Summary 应用层算分位数;但优先选 histogram
已有的 classic histogram 不想改造 配置 NHCB 摄入为 native 形态,但桶布局与 classic 一致

引自:Metric types | Understanding metric types

3.3 Jobs 与 Instances

3.3.1 术语定义

  • instance(实例):可被抓取的 endpoint,通常对应单个进程。
  • job(作业):一组用途相同的 instance(例如为可扩展性或可靠性而复制的进程)。

示例:一个 api-server job 有四个复制 instance:

instance 地址
instance 1 1.2.3.4:5670
instance 2 1.2.3.4:5671
instance 3 5.6.7.8:5670
instance 4 5.6.7.8:5671

3.3.2 自动附加的标签

抓取 target 时,Prometheus 自动附加两个 label 用于标识被抓取 target:

Label 值
job target 所属的已配置 job 名
instance 被抓取 target URL 的 <host>:<port> 部分

若被抓取的数据中已存在这两个 label,行为取决于配置项 honor_labels(详见 scrape_config 文档)。

3.3.3 每次抓取自动写入的时间序列

每次 instance 抓取,Prometheus 会在以下时间序列中存一个 sample:

指标 含义
up{job="<job-name>", instance="<instance-id>"} 健康(可达)为 1,抓取失败为 0;用于实例可用性监控
scrape_duration_seconds{job, instance} 抓取耗时
scrape_samples_post_metric_relabeling{job, instance} 应用 metric relabeling 后剩余的 sample 数
scrape_samples_scraped{job, instance} target 暴露的 sample 数
scrape_series_added{job, instance} 本次抓取新增序列的近似数量(New in v2.10)

启用 extra-scrape-metrics feature flag 后额外提供:

指标 含义
scrape_timeout_seconds{job, instance} target 配置的 scrape_timeout
scrape_sample_limit{job, instance} target 配置的 sample_limit;未配置限制时返回 0
scrape_body_size_bytes{job, instance} 最近一次成功抓取响应的未压缩大小;因超出 body_size_limit 导致的抓取失败报 -1,其他抓取失败报 0

引自:Jobs and instances

3.4 术语表

以下术语定义逐条来自官方 Glossary。

术语 定义
Alert Prometheus 中告警规则的产物,且处于**正在触发(actively firing)**状态;告警从 Prometheus 发送到 Alertmanager。
Alertmanager 接收 alerts,聚合成 groups,去重(de-duplicates),应用 silences,限流(throttles),再向 email、Pagerduty、Slack 等发送通知。
Bridge 从 client library 取样本并暴露给非 Prometheus 监控系统的组件;例如 Python、Go、Java 客户端可导出指标到 Graphite。
Client library 某语言(如 Go、Java、Python、Ruby)的库,便于直接对代码埋点、编写自定义 collectors 从其他系统拉取指标并暴露给 Prometheus。
Collector exporter 中代表一组指标的部分;直接埋点时可能是单个指标,从其他系统拉取时可能是多个指标。
Direct instrumentation 作为程序源码内联添加的埋点,使用 client library。
Endpoint 可被抓取的指标来源,通常对应单个进程。
Exporter 与目标应用并行运行的二进制,暴露 Prometheus 指标,通常是把非 Prometheus 格式的指标转换为 Prometheus 支持的格式。
Instance 唯一标识 job 中某个 target 的 label。
Job 具有相同目的的一组 targets 的集合,例如监控为扩展性或可靠性而复制的同类进程组。
Mixin 面向特定组件或系统的可复用、可扩展的 Prometheus alerts、recording rules 与 Grafana dashboards 集合;通常用 Jsonnet 打包,可组合以构建完整监控配置,实现同类基础设施组件的标准化监控。
Notification 代表一组一个或多个 alerts,由 Alertmanager 发送至 email、Pagerduty、Slack 等。
Promdash 曾是 Prometheus 的原生 dashboard builder,已弃用,被 Grafana 取代。
Prometheus 通常指 Prometheus 系统的核心二进制;也可指整个 Prometheus 监控系统。
PromQL Prometheus Query Language,支持聚合、切片切块(slicing and dicing)、预测与 joins 等广泛操作。
Pushgateway 持久化 batch jobs 最近一次推送的指标,使 Prometheus 可在其终止后再抓取这些指标。
Recording Rules 预计算高频需要或计算昂贵的表达式,并把结果保存为新的时间序列集合。
Remote Read Prometheus 特性,允许在查询中透明读取其他系统(如长期存储)的时间序列。
Remote Read Adapter 并非所有系统直接支持 remote read;适配器位于 Prometheus 与另一系统之间,转换双方的时间序列请求与响应。
Remote Read Endpoint 做 remote read 时 Prometheus 通信的目标端点。
Remote Write Prometheus 特性,允许将摄入样本实时发送到其他系统(如长期存储)。
Remote Write Adapter 并非所有系统直接支持 remote write;适配器位于 Prometheus 与另一系统之间,将 remote write 中的样本转换为对方可理解的格式。
Remote Write Endpoint 做 remote write 时 Prometheus 通信的目标端点。
Sample 时间序列中某一时间点的单个值;在 Prometheus 中每个 sample 由一个 float64 值与毫秒精度时间戳组成。
Silence Alertmanager 中的静默,阻止 labels 匹配该 silence 的 alerts 进入通知。
Target 要抓取对象的定义,例如应用哪些 labels、连接所需认证信息,以及其他定义抓取如何发生的信息。
Time Series 属于同一 metric 与同一组 labeled 维度的时间戳值流;Prometheus 把所有数据都存为时间序列。

术语分类速记

分类 术语
采集侧 Target、Endpoint、Exporter、Collector、Bridge、Client library、Direct instrumentation、Instance、Job
数据侧 Time Series、Sample、Metric types(Counter/Gauge/Histogram/Summary)、PromQL
告警侧 Alert、Alertmanager、Notification、Silence、Recording Rules
远程/扩展侧 Remote Read / Remote Write(+ Adapter / Endpoint)、Pushgateway、Mixin、Promdash

引自:Glossary


第 4 章 架构与设计

4.1 设计哲学与动机

4.1.1 设计文档入口(Design documents)

Problem statements and exploratory documents(问题陈述与探索性文档):有时会看向更远的潜在未来。此节文档多为探索性,应作为“影响集体思考”之物,而非具体或确定内容。

探索性文档 初始日期
Prometheus is not feature complete 2020-05
Thoughts about timestamps and durations in PromQL 2020-10
Prometheus, OpenMetrics & OTLP 2021-03
Prometheus Sparse Histograms and PromQL 2021-10
Quoting Prometheus names 2023-01

(每项均链接到对应 Google Docs 文档。)

4.1.2 核心设计动机

综合官方 Overview 与 FAQ,Prometheus 的设计动机可归纳为以下几点:

动机 具体体现
可靠性优先 作为故障时快速诊断的首选系统;每个 server 独立、不依赖网络存储或远程服务,基础设施其他部分损坏时仍可依赖;无需搭建大量基础设施
可靠地把告警送达人类 这是 Prometheus 最看重的取舍(出自 FAQ);代价是放弃 100% 准确性
多维数据模型 显式 key-value labels,而非把维度隐式编码进 metric name;便于过滤、分组、匹配、下钻
单节点自治,易于运行 主 server 以单个单体二进制独立运行,无外部依赖;单实例可扩展至数千万活跃序列
Pull 优先 HTTP pull 便于定位 target 是否 down、便于手动用浏览器检查健康;push 场景由 Pushgateway 兜底
面向动态环境 service discovery 适配高度动态的云原生/微服务架构

为什么选择 pull 而非 push(官方 FAQ 的完整理由):

理由 说明
灵活部署 可按需启动额外监控实例(如开发时在笔记本上)
判断 down 更可靠 更易且更可靠地判断 target 是否 down
便于人工排查 可手动用浏览器访问 target 检查健康

官方结论:整体上 pull 略优于 push,但不应作为选型的主要原因。必须 push 时,官方提供 Pushgateway。

💡 补充:Pull 模型的代价是“短生命周期任务”难以被抓到——这正是官方提供 Pushgateway 的原因(见术语表 Pushgateway)。

引自:Design documents | Overview | Frequently asked questions

4.2 整体架构与组件关系

4.2.1 数据流架构

官方 Overview 对架构的描述如下:

  • Prometheus 从被埋点的 jobs 抓取指标,可直接抓取;短生命周期任务则经中间 push gateway。
  • 所有抓取样本本地存储,并在该数据上运行 rules——用于聚合/记录新的时间序列,或生成告警。
  • 可用 Grafana 或其他 API 消费者可视化已采集的数据。
  • 官方架构配图:/assets/docs/architecture.svg。

Tutorials 教程给出的基本架构组件(更精简的视角):

组件 职责
Prometheus Server 抓取并存储指标数据的服务端
Targets to be scraped 被抓取目标,例如暴露自身指标的 instrumented application,或暴露其他应用指标的 exporter
Alertmanager 基于预设规则触发告警
(另有 push_gateway) 该教程未涉及,见术语表与第 4.2.3 节

4.2.2 组件清单(多数可选)

组件 仓库 / 说明
主 Prometheus server github.com/prometheus/prometheus,抓取并存储时间序列数据
Client libraries 用于给应用代码埋点
Pushgateway github.com/prometheus/pushgateway,支持短生命周期任务(short-lived jobs)
专用 Exporters 面向 HAProxy、StatsD、Graphite 等服务的指标导出器
Alertmanager github.com/prometheus/alertmanager,处理告警
各类支持工具 —

实现语言:多数组件用 Go 编写,便于以静态二进制构建与部署(部分组件用 Java、Python、Ruby,见 FAQ)。

4.2.3 端到端数据流示意

                        ┌──────────────────────────────┐
                        │      Prometheus Server        │
   ┌──────────┐  pull   │  ┌────────┐   ┌───────────┐  │
   │ 埋点应用  │ ◄───────┼──│ Scrape │──►│ 本地 TSDB  │  │
   │ /metrics │         │  └────────┘   └───────────┘  │
   └──────────┘         │        │            ▲        │
   ┌──────────┐  pull   │        ▼            │        │
   │ Exporter │ ◄───────┼──  Rules(recording / alerting)│
   └──────────┘         │        │                     │
   ┌──────────┐  push   │        ▼                     │
   │ 短生命周期│ ──────► │  ┌──────────────┐            │
   │   job    │ Pushgateway│ Alertmanager │            │
   └──────────┘         │  └──────┬───────┘            │
                        └─────────┼────────────────────┘
                                  ▼
                     email / PagerDuty / Slack / webhook ...
                        ▲
   ┌──────────┐  PromQL  │
   │ Grafana  │──────────┘ 或其它 API 消费者
   └──────────┘

💡 补充:上图为依据官方文字描述绘制的示意关系图,非官方原图;官方原图见 /assets/docs/architecture.svg。

引自:Overview | Getting started with Prometheus

4.3 Agent 模式(对比 Server 模式)

4.3.1 是什么

Prometheus Agent 是内置于 Prometheus 二进制中的一种运行模式,具有与 server 模式相同的 scraping APIs、语义、配置与发现机制。该模式:

  • 禁用 Prometheus 的一些常规功能:TSDB、alerting、rule evaluations;
  • 将二进制针对抓取与向远端 remote write 做优化;
  • 用一个定制化的 TSDB WAL 替代本地存储。

Remote Write 的角色:Prometheus Remote Write 协议把 Prometheus 采集到的全部或子集 metrics 转发(流式)到远端位置;你可以配置 Prometheus 把部分指标(如需,还可包含全部 metadata 和 exemplars)转发到一个或多个支持 Remote Write API 的位置。

为什么用 Pull + Remote Write:即便使用 Remote Write,Prometheus 仍用 pull 模型从应用采集指标,从而理解这些不同的失败模式。之后再把 samples 与 series 批量导出、复制(push)到 Remote Write endpoints,限制中心侧“监控未知量”的数量。

Global View 用例:从这样的 scraper 流式发送数据,使得把指标数据集中存于一处成为可能,从而支持 Global View 用例,实现关注点分离——当管理应用的团队与负责可观测性/监控 pipeline 的团队不同时尤为有用。

本质:Agent 模式为 remote write 用例优化 Prometheus,禁用查询、告警与本地存储,代之以定制 TSDB WAL。其余全部相同:scraping 逻辑、service discovery 与相关配置。如果你只想把数据转发到远端 Prometheus server 或任何兼容 Remote-Write 的项目,它可作为 Prometheus 的 drop-in replacement(直接替换)。

官方配图:./images/prometheus_agent.png。

4.3.2 Server 模式 vs Agent 模式对比

维度 Server 模式(默认) Agent 模式
本地查询 ✅ 支持 ❌ 不支持(无法查询本地实例)
Recording rules ✅ 支持 ❌ 不支持(规则必须在远端做)
告警(Alerting) ✅ 支持 ❌ 不支持(全部告警由远端系统完成)
本地存储 完整 TSDB 定制 TSDB WAL(成功后立即删除数据)
Scraping / SD / 配置 ✅ ✅ 完全相同
Remote Write ✅ ✅ 核心用途
Web UI 端口 9090 9095(禁用查询能力,但展示 build info、configuration、targets、service discovery 信息)
资源占用 常规 约为常规 server 的一小部分
存储路径 flag --storage.tsdb.path(默认 data/,仅 server 模式) --storage.agent.path(默认 data-agent/,仅 agent 模式)

4.3.3 Agent 模式的收益(Benefits)

收益 说明
更高效率 定制的 Agent TSDB WAL 在写入成功后立即移除数据。若无法到达远端 endpoint,则临时持久化到磁盘,直到远端恢复。目前仅限两小时缓冲,与非 agent 版 Prometheus 类似。这意味着无需在内存中构建 chunks、也无需维护用于查询的完整 index;Agent 模式使用的资源只是常规 Prometheus server 在类似情形下的一小部分
更易水平扩展摄入 Agent 模式使**摄取的水平扩展(horizontal scalability for ingestion)**更简单(见官方博客《The dream: auto-scalable metric ingestion》)

4.3.4 Agent 模式的代价(Downsides)

  • No local queries:你无法查询本地 Prometheus 实例。
  • Recording rules are not possible:无法为发送到 remote write 的数据做预聚合总结;规则必须在远端完成。
  • No alerting:全部告警都必须由远端系统完成。

4.3.5 怎么用

用 --agent flag 运行 Agent 模式。--help 输出中可见相关 flag:

usage: prometheus [<flags>]

The Prometheus monitoring server

Flags:
  -h, --help                     Show context-sensitive help (also try --help-long and --help-man).
      (... other flags)
      --storage.tsdb.path="data/"
                                 Base path for metrics storage. Use with server mode only.
      --storage.agent.path="data-agent/"
                                 Base path for metrics storage. Use with agent mode only.
      (... other flags)
      --[no-]agent               Run Prometheus in 'Agent mode'.

如何判断某 flag 属于哪个模式:其余 flag 要么两类模式共用,要么只属于某一模式。看该 flag 帮助字符串的最后一句即可:“Use with server mode only” 表示仅 server 模式;若没有任何此类说明,则该 flag 是共用的。

Agent 模式接受相同的 scrape 配置(含相同的 discovery 选项与 remote write 选项),并暴露 9095 端口的 Web UI——禁用查询能力,但展示 build info、configuration、targets 与 service discovery 信息,与常规 Prometheus server 一致。

引自:Prometheus Agent Mode

4.4 API 稳定性承诺

Prometheus 承诺在一个主版本内保持 API 稳定,并努力避免对关键特性做破坏性变更。部分特性(纯装饰性的、仍在开发中的、或依赖第三方服务的)不在此承诺范围内。

4.4.1 3.x 中被视为稳定的内容(Stable for 3.x)

# 稳定项
1 查询语言与数据模型(The query language and data model)
2 告警与 recording 规则(Alerting and recording rules)
3 摄入的 exposition 格式(The ingestion exposition format)
4 v1 HTTP API(被 dashboards 与 UIs 使用),不含显式标记为 experimental 的 endpoint
5 配置文件格式(减去 service discovery 的 remote read/write,见下)
6 规则/告警文件格式(Rule/alert file format)
7 Console template 语法与语义
8 Remote write 发送(依据 1.0 规范)与接收
9 Agent 模式
10 OTLP receiver endpoint

4.4.2 3.x 中被视为不稳定的内容(Unstable for 3.x)

任何被标记为 experimental 或 subject to change 的特性,包括:

  • double_exponential_smoothing PromQL 函数(见 https://github.com/prometheus/prometheus/issues/2458);
  • Remote read 与 remote read endpoint;
  • Server-side HTTPS 与 basic authentication;
  • Service discovery 集成,例外为 static_configs、file_sd_configs 和 http_sd_config;
  • 属于 server 一部分的包的 Go APIs;
  • Web UI 生成的 HTML;
  • Prometheus 自身 /metrics endpoint 中的 metrics;
  • 精确的磁盘格式(on-disk format)——潜在变更将向前兼容并由 Prometheus 透明处理;
  • 日志格式(The format of the logs)。

4.4.3 升级含义

  • Prometheus 2.x 的稳定性保证见 2.x 文档。
  • 只要你不使用标记为 experimental/unstable 的特性,在同一主版本内升级通常无需任何运维调整,破坏风险极低。
  • 任何破坏性变更都会在 release notes 中标记为 CHANGE。

4.4.4 稳定性等级速查

等级 含义 典型对象
Stable 主版本内保证稳定 查询语言、数据模型、规则格式、v1 HTTP API(非 experimental)、exposition 格式、remote write 1.0、Agent 模式、OTLP receiver
Experimental / Unstable 可能随时变更,不提供稳定保证 double_exponential_smoothing、remote read、server-side HTTPS/basic auth、多数 SD 集成、Go APIs、Web UI HTML、自身 /metrics、磁盘格式、日志格式

💡 补充:LTS 支持范围明确排除了上述不稳定特性(Unstable features)、实验性特性(Experimental features,见 feature_flags)以及 OpenBSD 支持。详见第 5.2 节。

引自:API stability guarantees | Long-term support


第 5 章 生态与版本

5.1 路线图

官方 Roadmap 说明:以下仅为近期计划实现的部分主要特性;更完整的计划与当前工作见各仓库 issue tracker(如 Prometheus server)。

计划特性 说明
Server-side metric metadata support 目前 metric types 及其他 metadata 仅在 client libraries 与 exposition format 中使用,未在 Prometheus server 持久化或利用。计划未来利用这些 metadata;第一步是在 Prometheus 内存中聚合该数据,并通过实验性 API 端点提供
Adopt OpenMetrics OpenMetrics 工作组正在制定新的指标暴露标准;计划在 client libraries 与 Prometheus 自身支持该格式
Retroactive rule evaluations 增加对回溯规则求值的支持,利用 backfill
TLS and authentication in HTTP serving endpoints TLS 与认证正逐步推广到 Prometheus、Alertmanager 与官方 exporters;该支持可让用户安全部署 Prometheus 组件而无需反向代理提供外部附加这些能力
Support the Ecosystem Prometheus 有一系列 client libraries 与 exporters,总有更多语言可支持、更多系统值得导出指标;将持续支持生态创建与扩展这些

引自:Roadmap

5.2 发布周期与 LTS 策略

5.2.1 LTS 定义

Prometheus LTS(Long-term support) 是经挑选的发布版本,在一年延长期内接收经过挑选的 bug 修复。

5.2.2 发布节奏

  • 每 6 周开启一个新的 minor release 周期;
  • 6 周后,某个 minor release 通常不再接收 bug 修复;
  • 因此,用户受某 minor release 的 bug 影响时,往往需升级到最新 Prometheus release。

5.2.3 升级

  • 得益于 API 稳定性保证,升级通常直接简单;
  • 但新特性与增强也可能带来回归,从而需要再次升级。

5.2.4 支持范围

项 规则
修复级别 LTS 版本仅接收高严重度问题的修复,即 CVSS 评分 7.0 或更高
可追加 可能追加 bug 修复或文档修复
工具链 构建工具链也会保持最新
承诺性质 此承诺为社区尽力而为(best effort),欢迎贡献

5.2.5 支持周期重叠

  • 两个相邻 LTS 版本的支持期应至少重叠一个月;
  • 目的:使依赖 Prometheus 的用户既限制升级风险,又有社区维护的 server。

5.2.6 LTS 发布列表

  • LTS 发布列表由占位符 <!-- LTS_RELEASES_TABLE --> 动态生成(源文件中无具体版本数据)。

5.2.7 LTS 支持的排除项(Limitations)

LTS 支持不覆盖:

排除项 说明
API 稳定性保证中列出的不稳定特性(Unstable features) 见第 4.4.2 节
实验性特性(Experimental features) 见 feature_flags
OpenBSD 支持 —

参考链接:

引自:Long-term support | API stability guarantees

5.3 学习资源

官方 Media 页面汇总的学习资源如下。

5.3.1 社区与聚合资源

资源 说明
专门 subreddit https://reddit.com/r/prometheusmonitoring,汇集全网 Prometheus 相关资源
Awesome Prometheus https://github.com/roaldnefs/awesome-prometheus,更全面的社区维护资源列表

5.3.2 Blogs

  • 本站 blog(https://prometheus.io/blog/);
  • SoundCloud 宣布 Prometheus 的博文(比本站更详尽);
  • Robust Perception 博客的 Prometheus 相关文章。

5.3.3 Tutorials

5.3.4 Podcasts and interviews

  • Prometheus on FLOSS Weekly 357(Julius Volz);
  • Prometheus and Service Monitoring(Changelog podcast,Julius Volz)。

5.3.5 Recorded talks

主题 讲者 / 场合
Prometheus: A Next-Generation Monitoring System Julius Volz 与 Björn Rabenstein,SREcon15 Europe, Dublin
同名演讲 Brian Brazil,FOSDEM 2016
What is your application doing right now? Matthias Gruter, Transmode
Prometheus workshop Jamie Wilkinson,Monitorama PDX 2015
Monitoring Hadoop with Prometheus Brian Brazil
Monitoring mit Prometheus(德语) Michael Stapelberg, Easterhegg 2016
Prometheus in der Praxis(德语) Jonas Große Sundrup, MRMCD 2016

5.3.6 Presentation slides

分组 标题 / 讲者
General Prometheus Overview(Brian Brazil)
General Systems Monitoring with Prometheus(Brian Brazil,Devops Ireland Meetup)
General OMG! Prometheus(Benjamin Staffin, Fitbit Site Operations)
Docker Prometheus and Docker(Brian Brazil,Docker Galway)
Python Better Monitoring for Python(Brian Brazil,Pycon Ireland)
Python Monitoring your Python with Prometheus(Brian Brazil,Python Ireland Meetup)

引自:Media

5.4 官方 FAQ 整理

以下按官方 Frequently asked questions 的三大分组(General / Instrumentation / Implementation)逐条整理,采用“问题(现象)→ 解答”的形式。

5.4.1 General(通用)

Q:什么是 Prometheus? A:开源系统监控与告警工具箱,生态活跃;是 Kubernetes 唯一直接支持的系统,也是云原生生态事实标准。

Q:与其他监控系统如何比较? A:见 comparison 页(本篇第 1.5 节已完整整理)。

Q:依赖什么?是否云原生? A:

  • 主 server 以单个单体二进制独立运行,无外部依赖;
  • 是云原生;
  • 服务发现集成多数工具与云;
  • 多维数据模型可扩展至数千万活跃序列(tens of millions of active series),可监控大型云原生部署;
  • 取舍上,Prometheus 最看重“可靠地把告警送达人类”。

Q:是否支持高可用(High availability)? A:是。在两台或多台独立机器上运行完全相同的 Prometheus server。Thanos 等系统可去重,许多支持 remote write 的外部系统也能去重;完全相同的告警会由 Alertmanager 去重;Alertmanager 通过互联多个实例构成集群支持高可用。

Q:“Prometheus 不扩展”(Prometheus doesn't scale)? A:常属营销说法。单实例可优于某些自称长期存储的方案;可靠运行数千万活跃序列没问题。若需更多,可参考 Scaling and Federating Prometheus 博客与 integrations 页的长期存储系统。

Q:用什么语言写的? A:多数组件用 Go,部分用 Java、Python、Ruby。

Q:稳定性承诺如何? A:

  • GitHub org 中达 1.0.0 的仓库大体遵循语义化版本(semantic versioning),破坏性变更以主版本递增表示;实验性组件例外,会在公告中明确标注;
  • 未达 1.0.0 的仓库通常也相当稳定;
  • 破坏性变更会在 release notes 标注 [CHANGE];无正式发布的组件会明确沟通。

Q:为什么用 pull 而非 push? A:HTTP pull 的优势——① 可按需启动额外监控实例(如开发时在笔记本上);② 更易且更可靠地判断 target 是否 down;③ 可手动用浏览器访问 target 检查健康。整体上 pull 略优于 push,但不应作为选型主要原因。必须 push 时提供 Pushgateway。

Q:如何把日志喂给 Prometheus? A:

  • 短答——别这么做,改用 Grafana Loki 或 OpenSearch;
  • 长答——Prometheus 收集处理 metrics,不是事件日志系统;若想从应用日志提取 Prometheus 指标,Loki 正是为此设计(见其 metric queries 文档)。

Q:作者是谁? A:最初由 Matt T. Proud 与 Julius Volz 私下发起,主要初期开发由 SoundCloud 资助;现由众多公司与个人维护扩展。

Q:许可证? A:Apache 2.0。

Q:Prometheus 的复数形式? A:经研究确定为 'Prometheis';记不住时可用 "Prometheus instances"。

Q:能否重载配置? A:可以。向进程发送 SIGHUP,或向 /-/reload 端点发 HTTP POST,即可重载并应用配置;各组件会尽量优雅处理失败的变更。

Q:能否发送告警? A:可以,用 Alertmanager;支持 email、多种原生集成,以及任何人都可添加集成的 webhook 系统。

Q:能否创建仪表盘? A:可以,生产环境推荐 Grafana;也有 Console templates。

Q:能否改时区?为何全用 UTC? A:为避免时区混淆(尤其涉及 daylight saving time,夏令时),内部独占使用 Unix time,所有组件展示用 UTC。UI 时区选择需谨慎设计,欢迎贡献(见 issue #500)。

5.4.2 Instrumentation(埋点)

Q:哪些语言有埋点库? A:有多种 client libraries,详见文档;想为新语言贡献客户端,见 exposition formats。

Q:能否监控机器? A:可以。Node Exporter 在 Linux 及其他 Unix 系统暴露大量机器级指标,如 CPU 使用率、内存、磁盘利用率、文件系统占用、网络带宽。

Q:能否监控网络设备? A:可以。SNMP Exporter 支持 SNMP 设备;工业网络还有 Modbus exporter。

Q:能否监控 batch jobs? A:可以,用 Pushgateway;另见 batch jobs 最佳实践。

Q:开箱即用可监控哪些应用? A:见 exporters and integrations 列表。

Q:能否通过 JMX 监控 JVM 应用? A:可以。对无法直接用 Java client 埋点的应用,可用 JMX Exporter,独立运行或作为 Java Agent。

Q:埋点的性能影响有多大? A:各客户端与语言不一。Java 基准显示:Java client 递增 counter/gauge 需 12-17ns(取决于竞争);除对延迟极敏感的代码外可忽略。

5.4.3 Implementation(实现)

Q:为何样本值都是 64 位浮点?

A:

  • 为简化设计限定为 64 位浮点;
  • IEEE 754 双精度二进制浮点格式支持整数精度至 2^53;
  • 原生 64 位整数仅在需要 2^53 以上、2^63 以下整数精度时才有帮助;
  • 原则上可实现不同样本值类型(含大整数,超过 64 位),但目前非优先;
  • 即便 counter 每秒递增一百万次,也需超过 285 年才会遇到精度问题。

5.4.4 FAQ 速查索引

分组 问题 一句话结论
General 什么是 Prometheus 开源监控与告警工具箱,云原生事实标准
General 依赖 / 云原生 单体二进制、无外部依赖、云原生
General 高可用 多台独立机器跑相同 server + Alertmanager 集群去重
General 不扩展? 营销说法;单实例可跑数千万活跃序列
General pull vs push pull 略优,但不作为选型主因;需 push 用 Pushgateway
General 日志 别喂日志,用 Grafana Loki 或 OpenSearch
General 许可证 Apache 2.0
General 重载配置 SIGHUP 或 POST /-/reload
General 时区 内部 Unix time,展示统一 UTC
Instrumentation 监控机器 Node Exporter
Instrumentation 网络设备 SNMP Exporter / Modbus exporter
Instrumentation batch jobs Pushgateway
Instrumentation JVM JMX Exporter(独立或 Java Agent)
Instrumentation 埋点开销 Java 约 12-17ns,通常可忽略
Implementation 为何 64 位浮点 简化设计;2^53 内整数精确;极端场景 285 年才出问题

引自:Frequently asked questions


附录:本篇覆盖清单

本篇内容来源与章节对照表(“无正文(导航页)”的小节不产出正文,仅在此备案)。

# 官网页面 URL 页面标题 类目 对应本篇章节目
1 https://prometheus.io/docs/introduction/overview/ Overview docs 1.1 / 1.3 / 1.4 / 4.2
2 https://prometheus.io/docs/introduction/first_steps/ First steps with Prometheus docs 2.3 / 2.5 / 2.6
3 https://prometheus.io/docs/introduction/index/ Introduction docs —(导航页,无正文)
4 https://prometheus.io/docs/introduction/glossary/ Glossary docs 3.4
5 https://prometheus.io/docs/introduction/faq/ Frequently asked questions docs 5.4(并散见于 1.1 / 2.6 / 3.1 / 4.1)
6 https://prometheus.io/docs/introduction/comparison/ Comparison to alternatives docs 1.5
7 https://prometheus.io/docs/introduction/roadmap/ Roadmap docs 5.1
8 https://prometheus.io/docs/introduction/release-cycle/ Long-term support docs 5.2 / 4.4.4
9 https://prometheus.io/docs/introduction/media/ Media docs 5.3
10 https://prometheus.io/docs/introduction/design-doc/ Design documents docs 4.1
11 https://prometheus.io/docs/concepts/data_model/ Data model docs 3.1
12 https://prometheus.io/docs/concepts/metric_types/ Metric types docs 3.2
13 https://prometheus.io/docs/concepts/jobs_instances/ Jobs and instances docs 3.3
14 https://prometheus.io/docs/concepts/index/ Concepts docs —(导航页,无正文)
15 https://prometheus.io/docs/prometheus/latest/getting_started/ Getting started core 2.4 / 2.5 / 2.6
16 https://prometheus.io/docs/prometheus/latest/installation/ Installation core 2.1 / 2.2 / 2.6
17 https://prometheus.io/docs/prometheus/ Prometheus(server 文档入口) core —(导航页,无正文)
18 https://prometheus.io/docs/prometheus/latest/prometheus_agent/ Prometheus Agent Mode core 4.3
19 https://prometheus.io/docs/prometheus/latest/stability/ API stability guarantees core 4.4 / 5.2.7
20 https://prometheus.io/docs/tutorials/getting_started/ Getting started with Prometheus docs 1.1 / 2.1 / 2.4.9 / 4.2.1
21 https://prometheus.io/docs/tutorials/understanding_metric_types/ Understanding metric types docs 3.2
22 https://prometheus.io/docs/tutorials/ Tutorials docs —(导航页,无正文)
23 https://prometheus.io/docs/guides/ Guides docs —(导航页,无正文)
24 https://prometheus.io/docs/alerting/ Alertmanager docs —(导航页,无正文)

说明:

  • 第 18、19 项(Agent Mode、API stability)为完成本篇第 4 章所需的补充素材,直接取自 handbook-src/raw/core/prometheus_agent.md 与 handbook-src/raw/core/stability.md。
  • 第 3、14、17、22、23、24 项以及 batch 中的 Concepts、Tutorials、Guides、Prometheus Server、Alertmanager 索引页均为导航/落地页,正文为空,无概念、命令、配置项或示例可提炼,故不产出正文内容。

第 1 篇结束。 下一篇《第 2 篇:PromQL 与查询》将展开查询基础、操作符、查询函数、示例、HTTP API 与 Remote Read API。