由于 Prometheus 是“拉”的方式主动监测,所以需要在 server 端指定被监控节点的列表。当被监控的节点增多之后,每次增加节点都需要更改配置文件,非常麻烦,我这里用 consul-template+consul 动态生成配置文件,这种方式同样适用于其他需要频繁更改配置文件的服务。另外一种解决方案是 etcd+confd,基本现在主流的动态配置系统分这两大阵营。consul-template 的定位和 confd 差不多,不过它是 consul 自家推出的模板系统。
1.普通实现方法
先看下普通配置下 Prometheus 的配置文件样例:
– job_name: ‘node-exporter’
static_configs:
– targets: [‘10.167.202.10:9100’]
labels:
hostname: ‘web1’
– targets: [‘10.167.202.11:9100’]
labels:
hostname: ‘web2’
– targets: [‘10.167.202.12:9100’]
labels:
hostname: ‘web3’
2. file_sd_config 实现方法
每次新加监控节点的时候,只需要添加一个新的 targets 即可,“hostname”是我自定义的一个 label 标签,方便区分。
当 targets 的数量达到几百上千之后,就产生一个问题,配置文件看起来就会特别冗余。所以有经验的运维人就会想到用 include 的方式,把其他的配置文件包含进来,这样就把一个大而冗余的主配置文件,切分成一个个小的配置文件。Prometheus 这里用的方法就是基于文件的服务发现–“file_sd_config”。我这里在prometheus下面新建了一个 conf.d 的目录,包含两个子配置文件,分别监控不同系统的机器,linux 和 windows 的机器:
在prometheus.yml 中加入如下的配置
– job_name: ‘linuxnode-discorvery’
file_sd_configs:
– files:
– /apps/prometheus/conf.d/linuxnode-discovery.json
– job_name: ‘windowsnode-discorvery’
file_sd_configs:
– files:
– /apps/prometheus/conf.d/windowsnode-discovery.json
file_sd_config 参考样例
子配置文件可以是 YAML 或 JSON 格式,我这里用的 JSON 格式,示例如下:
cat conf.d/lnode-discovery.json
[
{
“targets”: [“10.167.202.235:9100”],
“labels”: {
“hostname”: “test-01”
}
},
{
“targets”: [“10.167.202.199:9100”],
“labels”: {
“hostname”: “test-02”
}
}
]
启动服务后,如下: