consul在微服務(wù)中用于服務(wù)注冊(cè)與發(fā)現(xiàn)的卢厂,在prometheus中也可以用于被監(jiān)控對(duì)象的自動(dòng)發(fā)現(xiàn)疾渣,這樣就實(shí)現(xiàn)了在不修改prometheus配置文件漾肮、不重啟的情況下清焕,自動(dòng)發(fā)現(xiàn)exporter并將其加入到監(jiān)控范圍
運(yùn)行consul
可以去官網(wǎng)下載二進(jìn)制安裝包竟终,但這里我還是推薦使用docker蝠猬,快速上手
docker run -d --rm --name=consul -p 8500:8500 consul:1.15.4
瀏覽器訪問(wèn) IP:8500 到consul的services頁(yè)面,可見現(xiàn)在只有一個(gè)consul服務(wù):
運(yùn)行prometheus
修改默認(rèn)配置文件為如下內(nèi)容:
# ...
scrape_configs:
- job_name: "prometheus"
# 注釋掉之前靜態(tài)配置的內(nèi)容
# static_configs:
# - targets: ["localhost:9090"]
# 修改服務(wù)發(fā)現(xiàn)為 consul_sd_configs:
consul_sd_configs:
- server: 'consul_ip:8500'
services: ['node_exporter']
啟動(dòng)prometheus容器:
docker run -d -p 9090:9090 -v $(pwd)/prometheus.yml:/opt/bitnami/prometheus/conf/prometheus.yml --name prometheus --rm bitnami/prometheus
瀏覽器訪問(wèn) IP:9090 到prometheus的targets頁(yè)面统捶,目前也是一個(gè)target都沒(méi)有
將node_exporter注冊(cè)到consul
這里采用發(fā)HTTP請(qǐng)求的方式注冊(cè).先寫一個(gè)注冊(cè)的shell腳本
register_consul.sh:
#!/bin/bash
NodeExporterIP=""
NodeExporterPort=9200
ServiceID="node_exporter1" # 服務(wù)唯一標(biāo)記榆芦,隨便寫,只要保證唯一就行喘鸟,一般是uuid
ServiceName="node_exporter" # (一組)服務(wù)的名稱
consulIP=""
consulPort=8500
curl -X PUT -d '{
"id": "'$ServiceID'",
"name": "'$ServiceName'",
"address": "'$NodeExporterIP'",
"port": '$NodeExporterPort',
"tags": ["node_exporter"],
"checks": [
{
"http": "http://'$NodeExporterIP':'$NodeExporterPort'/metrics",
"interval": "10s"
}
]
}' http://$consulIP:$consulPort/v1/agent/service/register
注冊(cè)腳本可以寫到node_exporter的啟動(dòng)腳本中(比如systemctl的service或者單獨(dú)的shell腳本)匆绣,這樣就能在node_exporter啟動(dòng)時(shí),自動(dòng)注冊(cè)到consul
運(yùn)行腳本后到consul和prometheus頁(yè)面上就能發(fā)現(xiàn)剛剛注冊(cè)的服務(wù)和target:
注銷服務(wù)腳本迷守,deregister_consul.sh:
#!/bin/bash
ServiceID="node_exporter1"
consulIP=""
consulPort=8500
curl -X PUT http://$consulIP:$consulPort/v1/agent/service/deregister/$ServiceID
服務(wù)從consul注銷后犬绒,prometheus也會(huì)自動(dòng)將其從targets中移除