Prometheus 是一套开源的系统监控和警报工具包,由前 Google 工程师在 SoundCloud 于 2012 年创建。它的设计灵感来源于 Google 内部的 Borgmon 监控系统,专为微服务和容器化环境设计。
2016 年,Prometheus 加入 Cloud Native Computing Foundation (CNCF),成为继 Kubernetes 之后的第二个托管项目,2018 年正式毕业,标志着其成为云原生监控的事实标准。
Prometheus 的生态系统由多个组件组成,其中许多是可选的。核心组件是 Prometheus Server,负责抓取和存储时间序列数据。
主机级别指标(CPU、内存、磁盘)
黑盒探测(HTTP、DNS、TCP)
MySQL 数据库指标
Redis 缓存指标
Prometheus 将所有数据存储为时间序列:即属于同一指标名称和同一组标签维度的时间戳值流。每个时间序列由指标名称和一组键值对标签唯一标识。
只增不减的计数器,用于记录请求数、任务完成数、错误数等。
http_requests_total
可增可减的数值,用于记录内存使用率、温度、并发请求数等。
node_memory_usage_bytes
对观察结果进行采样,在可配置的桶(bucket)中进行统计。
http_request_duration_seconds_bucket
类似于直方图,但直接在客户端计算分位数(Quantiles)。
go_gc_duration_seconds{quantile="0.99"}
| 特性 | Histogram | Summary |
|---|---|---|
| 分位数计算 | 服务端计算 | 客户端计算 |
| 可聚合性 | ✅ 可聚合 | ❌ 不可聚合 |
| 配置 | 需要预定义 bucket | 需要预定义 quantile |
| 推荐场景 | 大多数场景 | 精确分位数需求 |
PromQL (Prometheus Query Language) 是 Prometheus 强大的函数式查询语言,允许用户实时选择和聚合时间序列数据。它支持多种数据类型,包括标量、向量和矩阵,并提供了丰富的函数库。
42。http_requests_total{job="api"}。http_requests_total{job="api"}[5m]。+ 加法- 减法* 乘法/ 除法% 取模^ 幂运算== 等于!= 不等于> 大于< 小于>= 大于等于<= 小于等于and 与(交集)or 或(并集)unless 排除(差集)sum 求和avg 平均值min/max 最小/最大值count 计数stddev 标准差topk/bottomk 前/后 K 个| 函数 | 说明 | 示例 |
|---|---|---|
rate() |
计算范围向量的每秒平均增长率 | rate(http_requests_total[5m]) |
irate() |
计算瞬时增长率(最后两个样本) | irate(http_requests_total[5m]) |
increase() |
计算范围内的增量 | increase(http_requests_total[1h]) |
histogram_quantile() |
计算直方图的分位数 | histogram_quantile(0.95, rate(http_request_duration_bucket[5m])) |
predict_linear() |
线性回归预测未来值 | predict_linear(node_filesystem_free_bytes[1h], 4*3600) |
absent() |
检测指标是否存在 | absent(up{job="api"}) |
label_replace() |
替换或添加标签 | label_replace(up, "host", "$1", "instance", "(.*):.*)") |
http_requests_total
选择所有名为 http_requests_total 的时间序列。
http_requests_total{job="api-server", handler="/api/comments"}
通过标签进行过滤。
rate(http_requests_total[5m])
计算过去 5 分钟内每秒的平均增长率。
irate(http_requests_total[5m])
使用最近两个样本计算瞬时增长率。
sum(http_requests_total) by (job)
按 job 标签求和。
avg(rate(http_requests_total[5m]))
计算平均请求率。
histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))
计算 95% 分位的请求延迟。
topk(5, sum(http_requests_total) by (instance))
获取请求数最多的前 5 个实例。
Prometheus 的警报分为两部分:Prometheus Server 中的警报规则(Alerting Rules)和 Alertmanager。警报规则定义触发条件,Alertmanager 负责处理、路由和发送通知。
groups:
- name: example
rules:
- alert: HighErrorRate
expr: rate(http_requests_total{status="5xx"}[5m]) > 0.5
for: 10m
labels:
severity: critical
annotations:
summary: "High error rate on {{ $labels.instance }}"
description: "{{ $labels.instance }} has a 5xx error rate of {{ $value | humanizePercentage }} for more than 10 minutes."
global:
smtp_smarthost: 'smtp.example.com:587'
smtp_from: 'alertmanager@example.com'
route:
group_by: ['alertname', 'cluster']
group_wait: 30s
group_interval: 5m
repeat_interval: 4h
receiver: 'team-email'
routes:
- match:
severity: critical
receiver: 'pagerduty'
receivers:
- name: 'team-email'
email_configs:
- to: 'team@example.com'
- name: 'pagerduty'
pagerduty_configs:
- service_key: '<service-key>'
Prometheus 支持多种服务发现机制,可以自动发现和监控目标实例,而无需手动配置每个目标。
自动发现 Kubernetes 集群中的 Pod、Service、Node 等资源
从 Consul 服务注册中心发现服务
发现 AWS EC2 实例
通过 DNS 查询发现目标
从文件读取目标列表(JSON/YAML)
静态配置目标列表
Prometheus 与 Kubernetes 完美集成,支持多种资源类型的自动发现:
scrape_configs:
- job_name: 'kubernetes-pods'
kubernetes_sd_configs:
- role: pod
relabel_configs:
# 只监控带有 prometheus.io/scrape 注解的 Pod
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
action: keep
regex: true
# 从注解获取抓取路径
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
action: replace
target_label: __metrics_path__
regex: (.+)
# 从注解获取抓取端口
- source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
action: replace
regex: ([^:]+)(?::\d+)?;(\d+)
replacement: $1:$2
target_label: __address__
| Role | 说明 |
|---|---|
node |
发现集群中的所有 Node |
pod |
发现所有 Pod 及其容器端口 |
service |
发现所有 Service 及其端口 |
endpoints |
发现 Service 对应的 Endpoints |
ingress |
发现所有 Ingress 资源 |
Relabeling 是 Prometheus 强大的标签重写机制,允许在抓取前后修改标签:
replace
替换标签值
keep
保留匹配的目标
drop
丢弃匹配的目标
labelmap
映射标签名称
labeldrop
删除匹配的标签
labelkeep
保留匹配的标签
Prometheus 内置了高性能的时间序列数据库 (TSDB),同时支持远程存储集成以实现长期数据保存。
采用高效压缩算法,每个样本平均只占用 1-2 字节
数据按时间分块存储,默认 2 小时一个 block
Write-Ahead Log 确保数据持久性和崩溃恢复
通过 --storage.tsdb.retention.time 配置
# 存储相关启动参数 ./prometheus \ --storage.tsdb.path=/data/prometheus \ --storage.tsdb.retention.time=30d \ --storage.tsdb.retention.size=50GB \ --storage.tsdb.wal-compression
Prometheus 支持通过远程写入/读取接口集成外部存储系统:
高可用 + 全局查询
多租户 + 水平扩展
高性能 + 低资源消耗
分布式时序数据库
# 远程写入配置示例
remote_write:
- url: "http://remote-storage:9201/write"
queue_config:
max_samples_per_send: 1000
batch_send_deadline: 5s
# 远程读取配置示例
remote_read:
- url: "http://remote-storage:9201/read"
read_recent: true
联邦允许一个 Prometheus 服务器从另一个 Prometheus 服务器抓取选定的时间序列,用于实现:
# 联邦配置示例
scrape_configs:
- job_name: 'federate'
honor_labels: true
metrics_path: '/federate'
params:
'match[]':
- '{job="prometheus"}'
- '{__name__=~"job:.*"}'
static_configs:
- targets:
- 'prometheus-dc1:9090'
- 'prometheus-dc2:9090'
Prometheus 提供多种安装方式,包括二进制文件、Docker 容器和包管理器。以下是常用的安装方法:
# 下载最新版本 wget https://github.com/prometheus/prometheus/releases/download/v2.50.0/prometheus-2.50.0.linux-amd64.tar.gz # 解压 tar -xzf prometheus-2.50.0.linux-amd64.tar.gz cd prometheus-2.50.0.linux-amd64 # 运行 Prometheus ./prometheus --config.file=prometheus.yml
docker run -d \
-p 9090:9090 \
-v ./prometheus.yml:/etc/prometheus/prometheus.yml \
prom/prometheus
global:
scrape_interval: 15s # 全局抓取间隔
evaluation_interval: 15s # 全局规则评估间隔
# Alertmanager 配置
alerting:
alertmanagers:
- static_configs:
- targets: ['localhost:9093']
# 规则文件
rule_files:
- "alert.rules.yml"
# 抓取配置
scrape_configs:
# 监控 Prometheus 自身
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
# 监控 Node Exporter
- job_name: 'node'
static_configs:
- targets: ['localhost:9100']
<what>_<unit> 命名规范rate() 代替 irate() 进行长期趋势分析