使用基于文件的服务发现来发现数据采集目标

Prometheus 提供了多种用于发现抓取目标的服务发现选项, 包括 Kubernetes, Consul 等。如果您使用系统当前不支持服务发现,则 Prometheus 的基于文件的服务发现机制可能会最好地满足您的用例,您可以在 JSON 文件中列出采集目标(以及有关这些目标的元数据)。

在本指南中,我们将:

  • 在本地安装并运行 PrometheusNode Exporter
  • 创建 targets.json 文件,为 Node Exporter 指定主机和端口信息
  • 安装并运行 Prometheus实例,该实例配置为使用 targets.json 文件发现 Node Exporter
' class="reference-link">

安装并运行 Node Exporter

请参阅使用 Node Exporter 监控 Linux 主机安装部分。

节点导出器在 9100 端口上运行。为确保节点导出器公开指标:

  1. curl http://localhost:9100/metrics

数据指标输出应该如下所示:

  1. # HELP go_gc_duration_seconds A summary of the GC invocation durations.
  2. # TYPE go_gc_duration_seconds summary
  3. go_gc_duration_seconds{quantile="0"} 0
  4. go_gc_duration_seconds{quantile="0.25"} 0
  5. go_gc_duration_seconds{quantile="0.5"} 0
  6. ...
' class="reference-link">

安装配置并运行 Prometheus

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

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

解压目录包含 prometheus.yml 配置文件。使用如下内容替换该文件:

  1. scrape_configs:
  2. - job_name: 'node'
  3. file_sd_configs:
  4. - files:
  5. - 'targets.json'

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

This configuration specifies that there is a job called node (for the Node Exporter) that retrieves host and port information for Node Exporter instances from a targets.json file.

创建 targets.json 文件并将此内容添加到其中:

  1. [
  2. {
  3. "labels": {
  4. "job": "node"
  5. },
  6. "targets": [
  7. "localhost:9100"
  8. ]
  9. }
  10. ]

NOTE: 在本指南中,为了简洁起见,我们将手动使用 JSON 服务发现配置。 但是,一般而言,我们建议您改用某种 JSON 生成程序或工具。

此配置指定一个带有 localhost:9100 目标的名为 node 的作业

现在你可以启动 Prometheus:

  1. ./prometheus

如果 Prometheus 成功启动,您应该在日志中看到如下行:

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

公开发现服务的数据指标

随着 Prometheus 的启动和运行,您可以使用 Prometheus 表达式浏览器检索 node 公开的指标。例如,如果您查询 [up{job="node"} 指标,则可以看到 Node Exporter 恰好被发现。

' class="reference-link">

动态更改目标列表

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

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

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

  1. [
  2. {
  3. "targets": [
  4. "localhost:9100"
  5. ],
  6. "labels": {
  7. "job": "node"
  8. }
  9. },
  10. {
  11. "targets": [
  12. "localhost:9200"
  13. ],
  14. "labels": {
  15. "job": "node"
  16. }
  17. }
  18. ]

保存更改后,Prometheus 将自动收到新目标列表的通知。up{job="node"} 数据指标将显示instance 标签分别为 localhost:9100localhost:9200 的两个实例,

' class="reference-link">

小结

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