Prometheus 入门第一步

欢迎来到 Prometheus!Prometheus 是一个监控平台,通过从受监控目标的指标 HTTP 端点抓取指标来收集数据。本指南将向您展示如何使用 Prometheus 安装、配置和监控我们的第一个资源。您将下载、安装并运行 Prometheus。您还将下载并安装一个 exporter,它们是在主机和服务上暴露时间序列数据的工具。我们的第一个 exporter 将是 Prometheus 本身,它提供了关于内存使用、垃圾回收等各种主机级别指标。

下载 Prometheus

下载适用于您平台的最新版 Prometheus,然后解压。

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

Prometheus 服务器是一个名为 prometheus 的独立二进制文件(在 Microsoft Windows 上是 prometheus.exe)。我们可以运行这个二进制文件并通过传递 --help 标志查看其选项的帮助信息。

./prometheus --help
usage: prometheus [<flags>]

The Prometheus monitoring server

. . .

在启动 Prometheus 之前,让我们先进行配置。

配置 Prometheus

Prometheus 的配置是 YAML 格式的。Prometheus 下载包中包含一个名为 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']

示例配置文件中有三个配置块:globalrule_filesscrape_configs

global 块控制 Prometheus 服务器的全局配置。这里有两个选项。第一个是 scrape_interval,它控制 Prometheus 抓取目标的频率。您可以针对单个目标覆盖此设置。在这种情况下,全局设置是每 15 秒抓取一次。evaluation_interval 选项控制 Prometheus 评估规则的频率。Prometheus 使用规则创建新的时间序列并生成告警。

rule_files 块指定了我们希望 Prometheus 服务器加载的任何规则文件的位置。目前我们还没有规则。

最后一个块 scrape_configs 控制 Prometheus 监控哪些资源。由于 Prometheus 本身也通过 HTTP 端点暴露自身的数据,它可以抓取并监控自身的健康状况。在默认配置中,有一个名为 prometheus 的作业,它抓取 Prometheus 服务器暴露的时间序列数据。该作业包含一个静态配置的目标,即 localhost 的端口 9090。Prometheus 期望在目标的 /metrics 路径下获取指标数据。因此,这个默认作业通过以下 URL 进行抓取:http://localhost:9090/metrics

返回的时间序列数据将详细描述 Prometheus 服务器的状态和性能。

有关配置选项的完整规范,请参阅配置文档

启动 Prometheus

要使用我们新创建的配置文件启动 Prometheus,请切换到包含 Prometheus 二进制文件的目录并运行

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

Prometheus 应该启动。您也可以在 http://localhost:9090 浏览关于自身的 상태 页面。等待约 30 秒,让它从自身的 HTTP 指标端点收集数据。

您还可以通过访问其自身的指标端点来验证 Prometheus 是否正在提供关于自身的指标:http://localhost:9090/metrics

使用表达式浏览器

让我们尝试查看 Prometheus 收集的一些关于自身的数据。要使用 Prometheus 内置的表达式浏览器,请访问 http://localhost:9090/graph 并在“Graph”选项卡中选择“Table”视图。

正如您可以从 http://localhost:9090/metrics 中了解到,Prometheus 关于自身导出的一个指标名为 promhttp_metric_handler_requests_total(Prometheus 服务器服务的 /metrics 请求总数)。继续,将其输入到表达式控制台中

promhttp_metric_handler_requests_total

这将返回多个不同的时间序列(以及每个时间序列记录的最新值),所有这些时间序列都具有指标名称 promhttp_metric_handler_requests_total,但带有不同的标签。这些标签表示不同的请求状态。

如果我们只对导致 HTTP 代码为 200 的请求感兴趣,可以使用此查询来检索该信息

promhttp_metric_handler_requests_total{code="200"}

要计算返回的时间序列数量,您可以这样写

count(promhttp_metric_handler_requests_total)

有关表达式语言的更多信息,请参阅表达式语言文档

使用图形界面

要绘制表达式的图表,请访问 http://localhost:9090/graph 并使用“Graph”选项卡。

例如,输入以下表达式,以绘制自抓取的 Prometheus 中返回状态码 200 的每秒 HTTP 请求率图表

rate(promhttp_metric_handler_requests_total{code="200"}[1m])

您可以尝试调整图表范围参数和其他设置。

监控其他目标

仅从 Prometheus 收集指标并不能很好地体现 Prometheus 的能力。为了更好地了解 Prometheus 的功能,我们建议查阅其他 exporter 的文档。使用 Node Exporter 监控 Linux 或 macOS 主机指标指南是一个很好的起点。

总结

在本指南中,您安装了 Prometheus,配置了一个 Prometheus 实例来监控资源,并学习了在 Prometheus 表达式浏览器中处理时间序列数据的一些基础知识。要继续学习 Prometheus,请查看概览,了解接下来可以探索的内容。

本文档是开源的。请通过提交问题或拉取请求来帮助改进它。