3. 配置静态服务发现
任务目标
在Prometheus中,服务发现决定了监控系统如何获知需要采集的目标地址。本案例通过修改prometheus.yml,使用static_configs配置多个静态监控目标(node_exporter),并验证Prometheus已正确发现并开始采集这些目标。
环境准备
本案例假设你已具备以下环境(若未安装,请先完成):
- Prometheus 2.x 已安装并可通过
prometheus命令启动 - 至少两个node_exporter实例运行在本机不同端口(如9100、9101),用于模拟多节点监控
启动两个node_exporter(分别监听9100和9101端口):
# 终端1
node_exporter --web.listen-address=":9100"
# 终端2
node_exporter --web.listen-address=":9101"
配置静态服务发现
编辑Prometheus主配置文件prometheus.yml,在scrape_configs下添加或修改一个job,使用static_configs列出所有需要监控的目标地址。以下为完整配置示例:
global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_configs:
- job_name: 'node_exporter_static'
static_configs:
- targets: ['localhost:9100', 'localhost:9101']
labels:
env: 'dev'
region: 'local'
配置说明:
targets:必填,目标地址列表,格式为host:port,可添加多个。labels:可选,为这些目标统一附加标签,便于后续查询区分。- 若需为不同目标设置不同标签,可拆分为多个
static_configs块。
启动与验证
使用修改后的配置启动Prometheus(若已在运行,需重启或发送SIGHUP信号重载配置):
prometheus --config.file=prometheus.yml
启动后,通过以下步骤验证服务发现是否生效:
- 检查Targets页面:浏览器访问
http://localhost:9090/targets,在node_exporter_staticjob下应看到两个端点localhost:9100和localhost:9101,State均为UP。 - 查询指标验证:访问
http://localhost:9090/graph,执行查询up{job="node_exporter_static"},预期返回两条时间序列,值均为1(表示采集正常)。 - 验证标签生效:执行查询
up{env="dev"},应同样返回上述两条序列,说明自定义标签已附加成功。
判定标准
- Targets页面中两个端点状态均为
UP,无DOWN或错误信息。 - Prometheus能够查询到
up指标且值为1,表明服务发现配置正确、采集链路通畅。 - 若修改
targets列表后重载配置(kill -HUP <prometheus_pid>),Targets页面能动态反映新增或移除的目标,无需重启进程。
常见问题
- Targets显示
DOWN:检查node_exporter是否正常运行、端口是否被占用、防火墙是否放行对应端口。 - 配置重载不生效:确认配置文件语法正确(可运行
promtool check config prometheus.yml校验),且Prometheus进程有权限读取该文件。