使用基于文件的服务发现来发现抓取目标

Prometheus 提供了多种 服务发现选项,用于发现抓取目标,包括 KubernetesConsul 和许多其他选项。如果您需要使用当前不支持的服务发现系统,您的用例可能最适合使用 Prometheus 的 基于文件的服务发现 机制,该机制使您能够在 JSON 文件中列出抓取目标(以及关于这些目标的元数据)。

在本指南中,我们将

  • 在本地安装和运行 Prometheus Node Exporter
  • 创建一个 targets.json 文件,指定 Node Exporter 的主机和端口信息
  • 安装和运行 Prometheus 实例,该实例配置为使用 targets.json 文件发现 Node Exporter

安装和运行 Node Exporter

请参阅 本节 使用 Node Exporter 监控 Linux 主机指标 指南。Node Exporter 在端口 9100 上运行。为了确保 Node Exporter 正在暴露指标

curl http://localhost:9100/metrics

指标输出应该看起来像这样

# HELP go_gc_duration_seconds A summary of the GC invocation durations.
# TYPE go_gc_duration_seconds summary
go_gc_duration_seconds{quantile="0"} 0
go_gc_duration_seconds{quantile="0.25"} 0
go_gc_duration_seconds{quantile="0.5"} 0
...

安装、配置和运行 Prometheus

像 Node Exporter 一样,Prometheus 是一个静态二进制文件,您可以通过 tarball 安装。下载最新版本 适用于您的平台并解压它

wget https://github.com/prometheus/prometheus/releases/download/v*/prometheus-*.*-amd64.tar.gz
tar xvf prometheus-*.*-amd64.tar.gz
cd prometheus-*.*

解压后的目录包含一个 prometheus.yml 配置文件。将该文件的当前内容替换为以下内容

scrape_configs:
- job_name: 'node'
  file_sd_configs:
  - files:
    - 'targets.json'

此配置指定有一个名为 node (用于 Node Exporter) 的任务,该任务从 targets.json 文件中检索 Node Exporter 实例的主机和端口信息。

现在创建该 targets.json 文件并将以下内容添加到其中

[
  {
    "labels": {
      "job": "node"
    },
    "targets": [
      "localhost:9100"
    ]
  }
]
注意: 在本指南中,为了简洁起见,我们将手动处理 JSON 服务发现配置。但总的来说,我们建议您使用某种 JSON 生成过程或工具来代替。

此配置指定有一个 node 任务,只有一个目标:localhost:9100

现在您可以启动 Prometheus

./prometheus

如果 Prometheus 已成功启动,您应该在日志中看到类似这样的一行

level=info ts=2018-08-13T20:39:24.905651509Z caller=main.go:500 msg="Server is ready to receive web requests."

探索已发现服务的指标

随着 Prometheus 启动并运行,您可以使用 Prometheus 表达式浏览器 探索由 node 服务暴露的指标。例如,如果您探索 up{job="node"} 指标,您可以看到 Node Exporter 正在被正确发现。

动态更改目标列表

当使用 Prometheus 基于文件的服务发现机制时,Prometheus 实例将监听文件的更改,并自动更新抓取目标列表,无需重启实例。为了演示这一点,启动第二个 Node Exporter 实例,端口为 9200。首先导航到包含 Node Exporter 二进制文件的目录,并在新的终端窗口中运行此命令

./node_exporter --web.listen-address=":9200"

现在修改 targets.json 中的配置,为新的 Node Exporter 添加一个条目

[
  {
    "targets": [
      "localhost:9100"
    ],
    "labels": {
      "job": "node"
    }
  },
  {
    "targets": [
      "localhost:9200"
    ],
    "labels": {
      "job": "node"
    }
  }
]

当您保存更改时,Prometheus 将自动收到新目标列表的通知。up{job="node"} 指标应显示带有 instance 标签 localhost:9100localhost:9200 的两个实例。

总结

在本指南中,您安装并运行了 Prometheus Node Exporter,并配置 Prometheus 以使用基于文件的服务发现来发现和抓取来自 Node Exporter 的指标。

本文档是开源的。请通过提交 issue 或 pull request 来帮助改进它。