使用基於檔案的服務發現來發現抓取目標

Prometheus 提供了多種用於發現抓取目標的 服務發現選項 ,包括 KubernetesConsul 等。如果您需要使用目前尚不支援的服務發現系統,Prometheus 的 基於檔案的服務發現 機制可能會最適合您的用例,該機制允許您在 JSON 檔案中列出抓取目標(以及關於這些目標的元資料)。

在本指南中,我們將

  • 在本地安裝並執行 Prometheus Node Exporter
  • 建立一個 targets.json 檔案,指定 Node Exporter 的主機和埠資訊
  • 安裝並執行一個配置為使用 targets.json 檔案發現 Node Exporter 的 Prometheus 例項

安裝並執行 Node Exporter

請參閱 使用 Node Exporter 監控 Linux 主機指標 指南中的 本節內容。Node Exporter 執行在 9100 埠。要確保 Node Exporter 正在暴露指標

curl https://: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 也是一個單一的靜態二進位制檔案,您可以透過 tar 包進行安裝。下載適用於您平臺的最新版本 並對其進行解壓

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 的程序或工具。

此配置指定了一個包含單個目標 localhost:9100node 作業。

現在您可以啟動 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 例項將監聽檔案的變化,並自動更新抓取目標列表,而無需重新啟動例項。為了演示這一點,請在 9200 埠上啟動第二個 Node Exporter 例項。首先導航到包含 Node Exporter 二進位制檔案的目錄,並在新的終端視窗中執行以下命令

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

現在透過為新的 Node Exporter 新增條目來修改 targets.json 中的配置

[
  {
    "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 的指標。

本頁內容