强曰为道
与天地相似,故不违。知周乎万物,而道济天下,故不过。旁行而不流,乐天知命,故不忧.
文档目录

Prometheus 完全指南 / 01 - Prometheus 简介

01 - Prometheus 简介

1.1 历史背景

Prometheus 最初由 SoundCloud 的前 Google 工程师于 2012 年开发,灵感来源于 Google 内部的监控系统 Borgmon。其名称取自希腊神话中的普罗米修斯——为人类带来火种的泰坦神。

发展时间线

时间里程碑
2012SoundCloud 内部开发,首次开源
2015发布 1.0 版本,社区快速增长
2016加入 CNCF,成为第二个孵化项目
2018从 CNCF 毕业,成为毕业项目
2020发布 2.0,全新 TSDB 存储引擎
20242.50+ 特性持续迭代,生态成熟

为什么选择 Prometheus?

与传统监控系统(Zabbix、Nagios)相比,Prometheus 具有以下核心优势:

  • 多维数据模型:基于时间序列(time series)和键值对标签(labels)
  • 强大的查询语言:PromQL 支持灵活的数据聚合与分析
  • 不依赖分布式存储:单节点自治,本地存储高效可靠
  • 基于 HTTP 的 Pull 模型:松耦合,易于集成
  • 丰富的生态:大量官方和社区 Exporter

1.2 Pull 模型 vs Push 模型

这是 Prometheus 与传统监控系统最核心的区别之一。

Pull 模型(拉取模式)

┌──────────────┐       HTTP GET /metrics       ┌──────────────┐
│  Prometheus  │ ─────────────────────────────► │  Target A    │
│   Server     │ ◄───────────────────────────── │  (App/Node)  │
│              │       返回指标数据              │              │
│              │                                └──────────────┘
│              │       HTTP GET /metrics       ┌──────────────┐
│              │ ─────────────────────────────► │  Target B    │
│              │ ◄───────────────────────────── │  (App/Node)  │
└──────────────┘       返回指标数据              └──────────────┘

工作方式:Prometheus Server 主动向目标(Target)发起 HTTP 请求,拉取 /metrics 端点的数据。

优势

  • 集中管理:所有抓取目标在 Server 端统一配置
  • 健康检测:抓取失败即表示目标不可用,天然具备健康检查
  • 无需服务发现客户端:Target 不需要知道 Prometheus 的地址
  • 易于调试:可以直接用 curl 访问 /metrics 查看原始数据

Push 模型(推送模式)

┌──────────────┐    POST /metrics/write     ┌──────────────┐
│  App A       │ ──────────────────────────► │  监控系统     │
└──────────────┘                             │  Server      │
┌──────────────┐    POST /metrics/write     │              │
│  App B       │ ──────────────────────────► │              │
└──────────────┘                             └──────────────┘

工作方式:应用程序主动将指标数据推送到监控系统。

适用场景

  • 短生命周期任务(如 CronJob、批处理)
  • 无法暴露 HTTP 端口的服务
  • 防火墙限制,Prometheus 无法直接访问目标

对比总结

维度Pull(Prometheus)Push(Graphite/InfluxDB)
连接方向Server → TargetTarget → Server
配置管理集中式分散式
健康检测天然支持需要额外机制
适用场景长期运行服务短期任务/批处理
调试难度低(直接 curl)中(需查看日志)
防火墙友好需要网络可达通常更友好

注意:Prometheus 主要使用 Pull 模型,但通过 Pushgateway 也支持 Push 模式,用于短期任务的监控。详见 第 12 章 Pushgateway


1.3 核心概念

在深入学习之前,理解以下核心概念非常重要。

时间序列(Time Series)

Prometheus 存储的所有数据都是时间序列。每个时间序列由 指标名称 和一组 标签 唯一标识。

http_requests_total{method="GET", handler="/api/users", status="200"}
│                    │                                              │
│                    └── 标签(Labels)键值对                       │
└── 指标名称(Metric Name)

指标(Metrics)

指标是被监控系统的可量化属性。例如:

指标名称类型含义
http_requests_totalCounterHTTP 请求总数
node_memory_MemFree_bytesGauge空闲内存大小
http_request_duration_secondsHistogramHTTP 请求耗时分布

作业与实例(Job and Instance)

# 一个 scrape_config 示例
scrape_configs:
  - job_name: 'my-service'       # 作业名称
    static_configs:
      - targets: ['host1:8080']  # 实例 1
      - targets: ['host2:8080']  # 实例 2
  • Job:一组相同功能的实例集合(如 “my-service”)
  • Instance:Job 中的单个目标(如 “host1:8080”)

Prometheus 会自动为每个时间序列添加以下标签:

标签来源示例
job配置中的 job_namemy-service
instance配置中的 targethost1:8080

1.4 适用场景

✅ 非常适合的场景

场景说明
微服务监控数百个服务的请求量、延迟、错误率(RED 方法)
容器/Kubernetes 监控原生支持 Kubernetes 服务发现
基础设施监控CPU、内存、磁盘、网络(通过 Node Exporter)
中间件监控MySQL、Redis、Kafka、Elasticsearch 等
自定义业务指标应用内埋点,监控业务 KPI

⚠️ 不太适合的场景

场景替代方案
日志收集与分析ELK Stack / Loki
高精度计费专用计费系统
大量事件(Events)追踪Jaeger / Zipkin
需要 100% 精确计数专用数据库

业务场景:电商系统监控

                   ┌─────────────────────────────────────────┐
                   │            Prometheus 监控体系            │
                   ├─────────────────────────────────────────┤
                   │                                         │
   ┌──────────┐    │   ┌──────────┐    ┌──────────────────┐ │
   │ 用户请求  │────┼──►│ API 网关  │───►│ 订单服务 (微服务) │ │
   └──────────┘    │   └──────────┘    └──────────────────┘ │
                   │         │                   │           │
                   │         ▼                   ▼           │
                   │   ┌──────────┐    ┌──────────────────┐ │
                   │   │ 请求速率  │    │ 订单创建数量      │ │
                   │   │ 响应延迟  │    │ 支付成功率        │ │
                   │   │ 错误率   │    │ 库存扣减延迟      │ │
                   │   └──────────┘    └──────────────────┘ │
                   │         ▲                   ▲           │
                   │         │                   │           │
                   │   [RED 方法]         [业务指标]         │
                   └─────────────────────────────────────────┘

RED 方法(适用于微服务):

  • Rate:请求速率
  • Error:错误率
  • Duration:请求延迟

USE 方法(适用于基础设施):

  • Utilization:资源使用率
  • Saturation:资源饱和度
  • Error:错误数量

1.5 Prometheus 生态全景

┌─────────────────────────────────────────────────────────────┐
│                    Prometheus 生态系统                        │
├─────────────┬───────────────┬──────────────┬────────────────┤
│  数据采集    │  数据存储      │  数据查询     │  数据展示       │
│             │               │              │                │
│ Exporter    │ 本地 TSDB     │ PromQL       │ Grafana        │
│ Pushgateway │ Thanos        │              │ Console        │
│ OTel Agent  │ Cortex        │              │ PromLens       │
│             │ Mimir         │              │                │
├─────────────┼───────────────┼──────────────┼────────────────┤
│  服务发现    │  告警管理      │  联邦与扩展   │  客户端库       │
│             │               │              │                │
│ K8s         │ Alertmanager  │ Federation   │ Go/Python/Java │
│ Consul      │ PagerDuty     │ Remote Write │ Ruby/Node/Rust │
│ DNS/Eureka  │ Slack/Email   │ Remote Read  │                │
└─────────────┴───────────────┴──────────────┴────────────────┘

1.6 与其他监控系统对比

特性PrometheusZabbixInfluxDBDatadog
数据模型多维标签层级结构标签标签
查询语言PromQL内置函数InfluxQL/Flux自有语法
存储方式本地 TSDB关系数据库TSM 引擎云端
部署模式自建自建自建SaaS
Pull/PushPull 为主Agent PushPushAgent Push
适用规模中大型中大型中大型任意
社区生态CNCF 标准成熟活跃商业支持
成本免费免费开源/商业商业付费

1.7 第一个 Prometheus 指标

在深入后续章节之前,先来体验一下 Prometheus 的工作方式。

安装一个简单的应用

// main.go - 简单的 Go 应用,暴露 Prometheus 指标
package main

import (
    "net/http"
    "github.com/prometheus/client_golang/prometheus"
    "github.com/prometheus/client_golang/prometheus/promhttp"
)

var httpRequests = prometheus.NewCounterVec(
    prometheus.CounterOpts{
        Name: "myapp_http_requests_total",
        Help: "Total number of HTTP requests",
    },
    []string{"method", "path"},
)

func init() {
    prometheus.MustRegister(httpRequests)
}

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        httpRequests.WithLabelValues(r.URL.Path, r.Method).Inc()
        w.Write([]byte("Hello, Prometheus!"))
    })
    http.Handle("/metrics", promhttp.Handler())
    http.ListenAndServe(":8080", nil)
}

使用 curl 查看指标

# 启动应用后,访问 /metrics 端点
curl http://localhost:8080/metrics

# 输出示例:
# HELP myapp_http_requests_total Total number of HTTP requests
# TYPE myapp_http_requests_total counter
myapp_http_requests_total{method="GET",path="/"} 5
myapp_http_requests_total{method="GET",path="/metrics"} 3

1.8 本章小结

要点说明
核心模型Pull 模型 + 多维时间序列
数据标识指标名称 + 标签键值对
查询语言PromQL(功能强大)
适用场景微服务、容器、基础设施监控
核心方法RED(微服务)、USE(基础设施)

扩展阅读


下一章02 - 安装与部署