使用基于文件的服务发现抓取 Target
Prometheus 提供了多种服务发现选项用于发现抓取 Target,适配包括 Kubernetes、Consul 在内的多种系统的服务发现功能。如果需要使用当前不支持的服务发现系统,Prometheus 的基于文件的服务发现(file-based service discovery) 机制可能更适合你的用例,该机制允许你通过提供抓取 Target(以及关于这些 Target 的元数据)的 JSON 文件进行服务发现。
本指南将涵盖以下内容:
- 安装并运行本地的 Prometheus Node Exporter
- 创建一个
targets.json
文件,指定 Node Exporter 的主机和端口信息 - 安装并运行配置为使用
targets.json
文件发现 Node Exporter 的 Prometheus 实例
安装并运行 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 summarygo_gc_duration_seconds{quantile="0"} 0go_gc_duration_seconds{quantile="0.25"} 0go_gc_duration_seconds{quantile="0.5"} 0...
安装、配置并运行 Prometheus
类似于 node_exporter,Prometheus 也是一个静态二进制文件,你可以通过 tarball 方式进行安装。下载最新版本并解压它:
wget https://github.com/prometheus/prometheus/releases/download/v*/prometheus-*.*-amd64.tar.gztar xvf prometheus-*.*-amd64.tar.gzcd 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
采集任务,具有一个 Target: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 已被成功发现。
动态更改 Target 列表
在使用 Prometheus 的基于文件的服务发现机制时,Prometheus 实例会监听文件更改并自动更新 Target 列表,而无需重新启动实例。要验证这一点,请启动第二个 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 将自动更新 Target 列表。up{job="node"}
指标应显示带有instance
标签的两个实例localhost:9100
和localhost:9200
。
总结
在本指南中,你安装并运行了一个 Prometheus Node Exporter,并配置了 Prometheus 使用基于文件的服务发现来发现并抓取来自 node_exporter 的指标。
该文档基于 Prometheus 官方文档翻译而成。