一、 簡介
prometheus配置檔案 prometheus.yml 裡配置需要監聽的服務時,是按服務名寫死的,如果後面增加了節點或者元件資訊,就得手動修改此配置,并重新開機 promethues;那麼能否動态的監聽微服務呢?Prometheus 提供了多種動态服務發現的功能,這裡以 consul 為例。
二、引入 consul 的好處
在沒有使用 consul 服務自動發現的時候,我們需要頻繁對 Prometheus 配置檔案進行修改,無疑給運維人員帶來很大的負擔。引入consul之後,隻需要在consul中維護監控元件配置,prometheus就能夠動态發現配置了。
三、Prometheus 支援的多種服務發現機制
#Prometheus資料源的配置主要分為靜态配置和動态發現, 常用的為以下幾類:
1)static_configs: #靜态服務發現
2)file_sd_configs: #檔案服務發現
3)dns_sd_configs: DNS #服務發現
4)kubernetes_sd_configs: #Kubernetes 服務發現
5)consul_sd_configs: Consul #服務發現
...
#在監控kubernetes的應用場景中,頻繁更新的pod,svc,等等資源配置應該是最能展現Prometheus監控目标自動發現服務的好處
四、安裝單節點consul
下載下傳consul檔案
https://www.consul.io/downloads
解壓
移動
給權限
檢視版
consul --version
Consul v1.10.1
Revision db839f18b
Protocol 2 spoken by default, understands 2 to 3 (agent will automatically use protocol >2 when speaking to compatible agents)
資料持久化
mkdir -p /app/consul/data
啟動指令
啟動指令
nohup consul agent -server -data-dir=/app/consul/data -node=agent-one -bind=172.17.9.47 -bootstrap-expect=1 -client=0.0.0.0 -ui > /app/consul/consul.log 2>&1 &
簡單單機版已經完成。
複雜點的有叢集版,賬号密碼認證等等,相關參考文檔
https://www.k8stech.net/post/prom-discovery-consul/
大佬版本講解真的是好
五、注冊主機到consul
由于機器比較多,需要批量添加
consul主要是添加和删除指令,都是使用接口調用
删除
curl -X PUT http://172.17.9.47:8500/v1/agent/service/deregister/dam02
添加
curl -X PUT -d '{"id": "'${host_name}'","name": "node-exporter","address": "'${host_addr}'","port":9100,"tags": ["dam"],"checks": [{"http": "http://'${host_addr}':9100/","interval": "5s"}]}' http://172.17.9.47:8500/v1/agent/service/register
批量添加可以使用下面腳本
hosts檔案格式
dam01 172.17.8.227
dam02 172.17.8.228
$ cat registry.sh # 腳本内容如下
#!/bin/bash
while read host_name host_addr
do
curl -X PUT -d '{"id": "'${host_name}'","name": "node-exporter","address": "'${host_addr}'","port":9100,"tags": ["dam"],"checks": [{"http": "http://'${host_addr}':9100/","interval": "15s"}]}' http://172.17.9.47:8500/v1/agent/service/register
done < hosts
執行這個腳本,就可以批量添加主機到consul裡面去。
六、配置prometheus自動發現
cat /usr/local/prometheus/prometheus.yml
#類似下面格式 這個server為consul的位址,根據标簽比對組
- job_name: 'dam-exporter'
consul_sd_configs:
- server: 'localhost:8500'
services: [dam-exporter]
#複雜一點,需要正規表達式
- job_name: dam-exporter
honor_labels: true
metrics_path: /metrics
scheme: http
consul_sd_configs:
- server: 172.17.9.47:8500
services: [dam-exporter]
relabel_configs:
- source_labels: ['__meta_consul_tags']
target_label: 'product'
- source_labels: ['__meta_consul_dc']
target_label: 'idc'
- source_labels: ['product']
regex: ",dam-exporter,"
action: keep