# Prometheus 知识学习手册 · 第 1 篇:入门与架构 > 基于 [prometheus.io 官方文档](https://prometheus.io/docs/introduction/overview/) 整理 > 文档版本: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.1 Prometheus 是什么](#11-prometheus-是什么) - [1.2 解决什么问题](#12-解决什么问题) - [1.3 核心特点](#13-核心特点) - [1.4 适用场景:何时该用、何时不该用](#14-适用场景何时该用何时不该用) - [1.5 竞品对比](#15-竞品对比) - [第 2 章 快速上手](#第-2-章-快速上手) - [2.1 环境要求](#21-环境要求) - [2.2 下载与安装](#22-下载与安装) - [2.3 5 分钟跑通](#23-5-分钟跑通) - [2.4 官方 Hello World 教程完整步骤](#24-官方-hello-world-教程完整步骤) - [2.5 验证安装成功](#25-验证安装成功) - [2.6 常见启动问题](#26-常见启动问题) - [第 3 章 核心概念](#第-3-章-核心概念) - [3.1 数据模型详解](#31-数据模型详解) - [3.2 四种指标类型](#32-四种指标类型) - [3.3 Jobs 与 Instances](#33-jobs-与-instances) - [3.4 术语表](#34-术语表) - [第 4 章 架构与设计](#第-4-章-架构与设计) - [4.1 设计哲学与动机](#41-设计哲学与动机) - [4.2 整体架构与组件关系](#42-整体架构与组件关系) - [4.3 Agent 模式(对比 Server 模式)](#43-agent-模式对比-server-模式) - [4.4 API 稳定性承诺](#44-api-稳定性承诺) - [第 5 章 生态与版本](#第-5-章-生态与版本) - [5.1 路线图](#51-路线图) - [5.2 发布周期与 LTS 策略](#52-发布周期与-lts-策略) - [5.3 学习资源](#53-学习资源) - [5.4 官方 FAQ 整理](#54-官方-faq-整理) - [附录:本篇覆盖清单](#附录本篇覆盖清单) --- ## 第 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](https://prometheus.io/docs/introduction/overview/) | [Frequently asked questions](https://prometheus.io/docs/introduction/faq/) | [Getting started with Prometheus](https://prometheus.io/docs/tutorials/getting_started/) ### 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](https://prometheus.io/docs/introduction/overview/) | [Getting started with Prometheus](https://prometheus.io/docs/tutorials/getting_started/) ### 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](https://prometheus.io/docs/introduction/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](https://prometheus.io/docs/introduction/overview/) | [Frequently asked questions](https://prometheus.io/docs/introduction/faq/) ### 1.5 竞品对比 本节基于官方 [Comparison to alternatives](https://prometheus.io/docs/introduction/comparison/) 页面整理,对比 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 维度,**无法下钻到具体问题实例**。 编码示例对比: ```text # Graphite/StatsD 编码(仅一个聚合值,丢失实例维度) stats.api-server.tracks.post.500 -> 93 ``` ```text # Prometheus 编码(假设三个 api-server 实例,可下钻到实例) api_server_http_requests_total{method="POST",handler="/tracks",status="500",instance=""} -> 34 api_server_http_requests_total{method="POST",handler="/tracks",status="500",instance=""} -> 28 api_server_http_requests_total{method="POST",handler="/tracks",status="500",instance=""} -> 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](https://prometheus.io/docs/introduction/comparison/) | [Frequently asked questions](https://prometheus.io/docs/introduction/faq/) --- ## 第 2 章 快速上手 ### 2.1 环境要求 - Prometheus 使用 **`Go`** 编写,**只需对应操作系统的编译二进制**即可运行。 - 运行只需两样东西:**二进制 + 配置文件**(配置文件使用 **YAML** 格式)。 - 官方为多数 Prometheus 组件提供**预编译二进制**(precompiled binaries)。 > 💡 补充(工程经验,非官方原文):Prometheus 官方只发布 Linux/macOS/Windows 的可执行文件,本身是静态编译的单一二进制,无需额外运行时依赖。生产环境建议运行在 Linux 服务器上,并为其预留独立的数据盘(TSDB 数据目录 `--storage.tsdb.path`,默认 `./data`)。 > 引自:[Installation](https://prometheus.io/docs/prometheus/latest/installation/) | [Getting started with Prometheus](https://prometheus.io/docs/tutorials/getting_started/) | [Getting started](https://prometheus.io/docs/prometheus/latest/getting_started/) ### 2.2 下载与安装 官方 Installation 页面给出的安装方式逐条如下。 #### 2.2.1 方式一:预编译二进制 - 为多数官方 Prometheus 组件提供预编译二进制,版本列表见 。 - 下载后解包: ```bash tar xvfz prometheus-*.tar.gz cd prometheus-* ``` - 服务器为**单一二进制** `prometheus`(Windows 下为 `prometheus.exe`)。用 `--help` 查看所有选项: ```bash ./prometheus --help usage: prometheus [] 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](https://quay.io/repository/prometheus/prometheus) 或 [Docker Hub](https://hub.docker.com/r/prom/prometheus/)。 - 最简启动(以示例配置启动并暴露 9090 端口): ```bash docker run -p 9090:9090 prom/prometheus ``` - **镜像使用 volume 存储实际 metrics**。生产部署**强烈建议使用 named volume**,以便升级时管理数据。 - **命令行参数注意**:镜像以若干默认命令行参数启动(可在 Dockerfile 中查看);若想追加参数,需**自行重新加上原有参数**,否则会被覆盖。 **挂载配置示例(二选一)**: ```bash # 只挂载单个配置文件 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` 目录,**容器重启即清空**;需设置持久化存储: ```bash 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 ``` **自定义镜像(把配置烤入镜像)**: ```Dockerfile FROM prom/prometheus ADD prometheus.yml /etc/prometheus/ ``` ```bash 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](https://prometheus.io/docs/prometheus/latest/installation/) ### 2.3 5 分钟跑通 这一节把“下载 → 写配置 → 启动 → 首次查询 → 用 UI”串成一条最小可用路径,素材来自官方 [First steps with Prometheus](https://prometheus.io/docs/introduction/first_steps/)。 #### 2.3.1 配置文件详解 Prometheus 配置为 **YAML**,下载包自带示例配置 `prometheus.yml`,注释以 `#` 前缀。 ```yaml 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` 端口 | - **默认抓取路径为 `/metrics`**,即完整 URL 为 。 #### 2.3.2 启动 ```bash ./prometheus --config.file=prometheus.yml ``` 启动后: - 可在 查看自身状态页; - 约需 **30 秒**采集自身 HTTP 指标端点数据; - 可在 验证。 #### 2.3.3 首次查询(表达式浏览器) 访问 ,选择 **"Table"** 标签页。 示例指标 `promhttp_metric_handler_requests_total`(Prometheus 自身已处理的 `/metrics` 请求总数): ```promql promhttp_metric_handler_requests_total ``` 返回若干时间序列(各带最新值):metric name 相同但 labels 不同,labels 用于标识不同请求状态。 只查看 HTTP `200`: ```promql promhttp_metric_handler_requests_total{code="200"} ``` 统计返回的时间序列数量: ```promql count(promhttp_metric_handler_requests_total) ``` #### 2.3.4 UI 使用(绘图界面) - 访问 的 **"Graph"** 标签页。 - 示例(每秒 200 状态码请求速率): ```promql rate(promhttp_metric_handler_requests_total{code="200"}[1m]) ``` - 在 (或 **Status → Target health**)查看各 target 健康状态。 #### 2.3.5 监控其他 target - 建议参考其他 exporter 文档,起点为官方指南 **`Monitoring Linux or macOS host metrics using a node exporter`**()。 > 引自:[First steps with Prometheus](https://prometheus.io/docs/introduction/first_steps/) ### 2.4 官方 Hello World 教程完整步骤 本节按官方 [Getting started](https://prometheus.io/docs/prometheus/latest/getting_started/)(核心文档中的 “Hello World” 式教程)的完整流程展开:下载并在本地运行 Prometheus,配置其抓取自身与一个示例应用,再通过查询、规则、图表使用采集到的时序数据。 #### 2.4.1 步骤 1:下载并解包 ```bash tar xvfz prometheus-*.tar.gz cd prometheus-* ``` #### 2.4.2 步骤 2:编写自监控配置 保存为 `prometheus.yml`: ```yaml 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:启动 ```bash ./prometheus --config.file=prometheus.yml ``` - 默认数据库存于 `./data`(flag `--storage.tsdb.path`)。 - 状态页: - metrics 端点: #### 2.4.4 步骤 4:用表达式浏览器探索数据 访问 并选择 **"Graph"** 标签页: ```promql prometheus_target_interval_length_seconds ``` ```promql prometheus_target_interval_length_seconds{quantile="0.99"} ``` ```promql count(prometheus_target_interval_length_seconds) ``` 其中 `prometheus_target_interval_length_seconds` 表示 target 抓取之间的实际耗时。 绘图示例: ```promql rate(prometheus_tsdb_head_chunks_created_total[1m]) ``` #### 2.4.5 步骤 5:启动示例 target(Node Exporter) ```bash 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: ```yaml scrape_configs: - job_name: 'node' scrape_interval: 5s static_configs: - targets: ['localhost:8080', 'localhost:8081'] labels: group: 'production' - targets: ['localhost:8082'] labels: group: 'canary' ``` 在 或 **Status → Target health** 查看:三个端点状态应为 `UP`;若为 `DOWN`,检查对应端口上 Node Exporter 是否仍在运行。 示例返回序列: ```promql 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`: ```yaml 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` 信号。 ```bash kill -s SIGHUP ``` **优雅关闭**(推荐用信号/中断): - Linux 上发送 `SIGTERM` 或 `SIGINT`: ```bash kill -s ``` - 或在控制终端按中断字符(默认 `^C`)。 > 💡 补充(来自官方 FAQ):除 `SIGHUP` 外,也可向 `/-/reload` 端点发 **HTTP POST** 重载配置;各组件会尽量**优雅处理失败的变更**。 > 引自:[Getting started](https://prometheus.io/docs/prometheus/latest/getting_started/) | [Frequently asked questions](https://prometheus.io/docs/introduction/faq/) #### 2.4.9 Tutorials 版快速上手(含 node_exporter) 官方 [Tutorials → Getting started with Prometheus](https://prometheus.io/docs/tutorials/getting_started/) 给出了更精简的版本: **第一步:只抓取自身。** ```yaml global: scrape_interval: 15s scrape_configs: - job_name: prometheus static_configs: - targets: ["localhost:9090"] ``` 含义:`scrape_interval` 定义抓取频率;`scrape_configs` 含 job 名称与抓取目标。Prometheus 默认监听 **9090** 端口,故把 `localhost:9090` 加入 targets。 启动: ```bash prometheus --config.file=prometheus.yml ``` 此时 Prometheus 已运行并**每 15s 抓取自身指标**。 **第二步:接入 node exporter。** 先运行 exporter(机器指标 exporter,下载:): ```bash ./node_exporter ``` 再加入 `scrape_configs`: ```yaml 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](https://prometheus.io/docs/tutorials/getting_started/) ### 2.5 验证安装成功 | 检查项 | 方法 | 预期结果 | | --- | --- | --- | | 进程已启动 | 访问 | 能看到自身状态页 | | metrics 端点正常 | 访问 | 返回文本格式指标(约启动 30 秒后有数据) | | 目标健康 | 或 **Status → Target health** | `prometheus` target 状态为 `UP` | | 查询可用 | 选 Table,执行 `promhttp_metric_handler_requests_total` | 返回带不同 labels 的多条时间序列 | | 规则已加载(配置规则后) | | 能看到已定义的 record/alert 规则 | | 告警可查(接入 Alertmanager 后) | | 能看到告警及状态 | > 引自:[First steps with Prometheus](https://prometheus.io/docs/introduction/first_steps/) | [Getting started](https://prometheus.io/docs/prometheus/latest/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](https://prometheus.io/docs/introduction/first_steps/) | [Installation](https://prometheus.io/docs/prometheus/latest/installation/) | [Getting started](https://prometheus.io/docs/prometheus/latest/getting_started/) | [Frequently asked questions](https://prometheus.io/docs/introduction/faq/) --- ## 第 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(记法) 标准记法: ```text {