本章内容如下:

Prometheus 介绍
Prometheus 部署和配置
Node Exporter 采集数据
Pushgateway 采集数据
PromQL 查询语言
Grafana 图形化展示
Prometheus 标签管理
Prometheus 告警机制
Prometheus 服务发现
各种 Exporter 高级功能
Prometheus 实现容器监控
Prometheus 联邦 Federation
Prometheus 远程存储 VictoriaMetrics
Kubernetes 集成 Prometheus
总体总结

一、核心定位

Prometheus 以 “采集并存储时间序列数据,通过规则引擎分析数据并触发告警” 为核心目标,专注于解决分布式系统下的 “可观测性” 问题 —— 即帮助运维 / 研发团队实时掌握系统的运行状态(如服务器资源、服务性能、业务指标等),快速定位故障根源。

二、核心组件及架构

Prometheus 采用模块化架构,核心组件可按需组合,典型架构如下:

组件名称 核心功能
Prometheus Server 核心组件,负责从目标(Targets)采集指标、存储时间序列数据、执行查询和告警规则。
Exporters 指标采集器,将非 Prometheus 格式的指标(如服务器 CPU、MySQL 性能、Nginx 连接数)转换为标准格式并暴露给 Server。常见 Exporters:
node_exporter:采集服务器硬件 / 系统指标(CPU、内存、磁盘等)
mysql_exporter:采集 MySQL 数据库指标(连接数、慢查询、主从同步状态等)
nginx_exporter:采集 Nginx 性能指标(请求量、响应时间、错误率等)
Alertmanager 告警管理组件,接收 Server 触发的告警,负责去重、分组、路由(如推送到钉钉、邮件、Slack)及告警升级。
Grafana 可视化组件(非 Prometheus 官方核心组件,但必配),通过连接 Prometheus 数据源,生成仪表盘(Dashboard),支持折线图、柱状图等多种可视化形式,直观展示指标趋势。
Pushgateway 指标推送网关,用于采集 “短生命周期任务”(如临时脚本、批处理任务)的指标 —— 这类任务存在时间短,Server 来不及主动采集,可先推送到 Pushgateway,再由 Server 定期拉取。
Service Discovery 服务发现组件,自动发现待监控的目标(如 K8s 集群中的 Pod、服务),无需手动配置 Targets,适配动态变化的云原生环境。

三、核心工作原理(“拉取式” 监控流程)

Prometheus 采用 **“主动拉取(Pull)”** 为核心的监控模式,流程可分为 4 步:

  1. 指标暴露:Exporters 部署在目标机器 / 服务上,通过 HTTP 接口(默认/metrics)暴露标准化指标(如node_cpu_seconds_total{cpu="0",mode="idle"} 12345)。
  2. 指标采集:Prometheus Server 按配置的 “采集间隔”(如 15 秒),主动向 Exporters/Pushgateway 的/metrics接口发起 HTTP 请求,拉取指标数据。
  3. 数据存储:拉取的指标以 “时间序列数据(Time Series)” 格式存储在本地 TSDB(时序数据库)中,每条时间序列由 “指标名 + 标签(Labels)” 唯一标识(如http_requests_total{method="GET",path="/login"}),同时关联时间戳和指标值。
  4. 分析与告警
  • 查询分析:通过 PromQL(Prometheus Query Language,专用查询语言)对 TSDB 中的数据进行实时查询(如计算 “5 分钟内的平均请求响应时间”),并在 Grafana 中展示。
  • 告警触发:Server 定期执行 “告警规则”(如 “CPU 使用率连续 5 分钟超过 80%”),当指标满足规则条件时,生成告警并发送给 Alertmanager,由其完成告警分发。

四、核心特性

  1. 强大的时间序列数据模型:基于 “指标名 + 标签” 的二维模型,支持多维度筛选(如按 “服务名”“环境”“节点” 过滤指标),灵活适配复杂业务场景。
  2. 灵活的查询语言 PromQL:支持聚合(sum/avg)、过滤(==/!=)、时间范围([5m])等操作,可快速计算衍生指标(如rate(http_requests_total[5m])计算 5 分钟内的请求速率)。
  3. 高效的本地存储:内置 TSDB 针对时序数据优化,支持数据压缩(压缩率可达 10:1),单节点可存储数月数据,同时支持对接远程存储(如 Thanos、Cortex)实现海量数据持久化。
  4. 原生支持服务发现:适配 K8s、Consul、etcd 等主流服务发现机制,自动适配动态扩缩容的云原生环境,无需手动维护监控目标列表。
  5. 轻量且易部署:所有组件均为独立二进制文件,无复杂依赖,支持容器化部署(Docker/K8s),单节点即可快速搭建基础监控体系。
  6. 开放性生态:支持数百种 Exporters(覆盖数据库、中间件、云服务等),且可自定义 Exporter(如用 Python/Go 开发业务指标采集器),与 Grafana、Alertmanager 等工具无缝集成。

五、典型应用场景

  1. 云原生 / 容器监控:监控 K8s 集群的 Pod、Node、Service 状态(如 Pod 重启次数、Node 资源使用率),以及容器内服务的性能指标(如容器 CPU / 内存占用、应用响应时间)。
  2. 传统 IT 基础设施监控:通过node_exporter监控物理机 / 虚拟机的硬件资源(CPU、内存、磁盘 IO、网络带宽),通过mysql_exporter/redis_exporter监控数据库、缓存等中间件。
  3. 业务指标监控:自定义 Exporter 采集业务指标(如订单量、支付成功率、用户在线数),结合系统指标实现 “业务 - 系统” 全链路监控。
  4. 告警与故障排查:通过定制化告警规则(如 “支付接口错误率> 1% 触发 P1 告警”),结合 PromQL 查询和 Grafana 可视化,快速定位故障(如 “某节点磁盘满导致服务响应延迟”)。

六、与传统监控工具(如 Zabbix)的核心区别

Prometheus 与传统监控工具的差异主要源于 “云原生时代的需求适配”,具体对比如下:

维度 Prometheus Zabbix(传统监控)
监控模式 主动拉取(Pull)为主,支持推送(Pushgateway) 被动监听(Agent 推送)为主
数据模型 时间序列 + 标签(多维度) 键值对(单维度)
动态适配性 原生支持服务发现,适配 K8s 动态扩缩容 需手动配置监控目标,动态场景适配成本高
部署复杂度 轻量,单节点可部署,容器化友好 架构复杂(Server/Agent/DB 分离),部署成本高
查询能力 PromQL 灵活强大,支持复杂聚合与多维度分析 自定义查询能力弱,依赖预设模板
生态适配 深度集成云原生生态(K8s/Docker) 更适配传统物理机 / 虚拟机环境

正片开始

1.Prometheus 介绍

官方文档:

https://prometheus.io/docs/
https: //prometheus.io/docs/introduction/overview/
Prometheus 的主要模块包括:
●prometheus 时序数据存储、监控指标管理
●可视化
Prometheus web UI : 集群状态管理、 promQL
Grafana: 非常全面的可视化套件
●数据采集
Exporter: 为当前的客户端暴露出符合 Prometheus 规格的数据指标 ,Exporter 以守护进程的模式运行井开始采集数据,Exporter 本身也是一个 http_server 可以对 http 请求作出响应返回数据 (K/V 形式的metrics)
Pushgateway : 拉模式下数据的采集工具
●监控目标 服务发现 : 文件方式、 dns 方式、 console 方式、 k8s 方式
●告警: alertmanager
Prometheus 由几个主要的软件组件组成,其职责概述如下:

工作流程

●Prometheus server 定期从配置好的 jobs 或者 exporters 中拉取 Pull metrics ,或者接收来自
  Pushgateway 发过来的 metrics ,或者从其他的 Prometheus server 中拉 metrics
●Prometheus server 在本地存储收集到的 metrics ,并运行已定义好的 alert rules ,记录新的时间    序列或者向 Alertmanager 推送警报,实现一定程度上的完全冗余功能。
●Alertmanager 根据配置文件,对接收到的警报进行去重分组,根据路由配置,向对应主机发出      告警。
●集成Grafana 或其他 API 作为图形界面,用于可视化收集的数据。


Prometheus 只负责时序型指标数据的采集及存储

2.Prometheus 部署和配置

①ubuntu包安装

apt install prometheus            其他安装略

# 访问如下链接可以看到如下显示
http://<prometheus 服务器 IP>:9090

# 浏览器访问prometheus的指标 :
http://<prometheus 服务器 IP>:9090/metrics

Dashboard 菜单说明

我们选择一个监控项"scrape_duration_seconds",然后点击"Execute",查看效果

查看所有的监控项: 10.0.0.203:9090/api/v1/label/__name__/values

API访问

https://prometheus.io/docs/prometheus/latest/management_api/
https://prometheus.io/docs/prometheus/latest/querying/api/

注意: {ip:port} Prometheus 所在的 IP 和端口
●健康检查 GET {ip:port}/-/healthy  该端点始终返回200 ,应用于检查 Prometheus 的运行状况。
●准备检查 GET {ip:port}/-/ready    当Prometheus 准备服务流量(即响应查询)时,此端点返回 200
●加载配置 PUT {ip:port}/-/reload   POST {ip:port}/-/reload
●关闭服务  PUT {ip:port}/-/quit      POST {ip:port}/-/quit

[root@ubuntu2204 ~] #cat /lib/systemd/system/prometheus.service
......
[Service]
ExecStart = /usr/local/prometheus/bin/prometheus --
config .file = /usr/local/prometheus/conf/prometheus.yml --web .enable-lifecycle
......

[root@ubuntu2204 ~] #curl http://prometheus.wang.org:9090/-/healthy
[root@ubuntu2204 ~] #curl http://prometheus.wang.org:9090/-/ready

优化配置
Prometheus 命令支持选项如下:
https://prometheus.io/docs/prometheus/latest/command-line/prometheus/

②Node Exporter 安装  

其他安装方式略

安装 Node Exporter 用于收集各 node 主机节点上的监控指标数据,监听端口为 9100
 
github 链接   https://github.com/prometheus/node_exporter
官方下载   https://prometheus.io/download/
在需要监控的所有节点主机上进行安装
[root@node1 ~]#wget -P /usr/local/ 
https://github.com/prometheus/node_exporter/releases/download/v1.2.2/node_exporter-
1.2.2.linux-amd64.tar.gz 
[root@node1 ~]#cd /usr/local
[root@node1 local]#tar xvf node_exporter-1.2.2.linux-amd64.tar.gz 
[root@node1 local]#ln -s node_exporter-1.2.2.linux-amd64 node_exporter
[root@node1 local]#cd node_exporter
[root@node1 node_exporter]#mkdir bin
[root@node1 node_exporter]#mv node_exporter bin/
[root@node1 ~]#useradd -r -s /sbin/nologin prometheus 
[root@node1 ~]#chown -R prometheus:prometheus /usr/local/node_exporter/
Prometheus 采集 Node Exporter 数据
修改 Prometheus 配置文件

关键点儿提炼:

- job_name: 'node_exporter'   #添加以下行,指定监控的node exporter节点
  metrics_path: /metrics      #指定路径,此为默认值,可省略
  scheme: http                #指定协议,此为默认值,可省略
  static_configs:  
- targets: ['10.0.0.104:9100','10.0.0.105:9100','10.0.0.106:9100']

个人实际实践,只需要在原有的node上添加即可

Prometheus 验证 Node 节点状态数据 node_cpu_seconds_total

监控Grafana

③Pushgateway 采集自定义数据

官方连接: https://prometheus.io/docs/practices/pushing/
Pushgateway 是一项中介或代理服务,允许您从无法抓取的作业中推送指标,虽然有很多的Exporter 提供了丰富的数据 , 但生产环境中仍需要采集用户自定义的数据 , 可以利用 Pushgateway
实现
Pushgateway 是另⼀种采⽤客户端主动推送数据的方式 , 也可以获取监控数据的 prometheus 插件
Pushgateway exporter 不同 , Exporter 是被动采集数据
Pushgateway 可以单独运⾏在任何节点上,并不⼀定要在被监控客户端安装,用户⾃定义的脚本或程序将需要监控的数据推送给 Pushgateway , 然后 prometheus server 再向pushgateway拉取数据
Pushgateway 缺点

1.配置 Prometheus 收集 Pushgateway 数据

2.配置客户端发送数据给 Pushgateway

# 下面为发送一次数据 , 如果想周期性发送 , 可以通过 cron 或脚本循环实现
[root@ubuntu2004 ~] #echo "age 18" | curl --data-binary @- http://10.0.0.200:9091/metrics/job/pushgateway/instance/`hostname -I`
# 说明
10.0.0.200:9091   # 安装为 Pushgateway 主机的 IP 和端口
pushgateway   # 指定 jobname, 会自动添加一个新标签名称为 exported_pushgateway
`hostname -I` # 取当前主机的 IP instance 名称
@file # 表示从 file 中读取数据
@-     # 表示从标准输入读取数据
范例:通用脚本(是一个无限循环脚本)
#!/bin/bash

# 监控配置
METRIC_NAME="login_number"
METRIC_VALUE_CMD="who | wc -l"
METRIC_TYPE="gauge"
METRIC_HELP="Current login user count"

# Pushgateway配置
PUSHGATEWAY_HOST="10.0.0.200:9091"  # 修改为您实际的Pushgateway地址
EXPORTED_JOB="login_monitor"
INSTANCE=$(hostname -I | awk '{print $1}')
SLEEP_INTERVAL=5  # 推送间隔(秒)

# 推送函数
push_metric() {
    while true; do
        VALUE=$(eval "$METRIC_VALUE_CMD")
        
        echo "Pushing metric: ${METRIC_NAME} ${VALUE}"
        
        cat <<EOF | curl --max-time 5 --data-binary @- \
            "http://${PUSHGATEWAY_HOST}/metrics/job/${EXPORTED_JOB}/instance/${INSTANCE}"
# HELP ${METRIC_NAME} ${METRIC_HELP}
# TYPE ${METRIC_NAME} ${METRIC_TYPE}
${METRIC_NAME} ${VALUE}
EOF
        
        sleep ${SLEEP_INTERVAL}
    done
}

# 启动推送
push_metric

3.PromQL

Prometheus 提供一个内置的函数式的表达式语言PromQL(Prometheus Query Language),可以帮助用户实现实时地查找和聚合时间序列数据。

PromQL 表达式计算结果可以在图表中展示,也可以在 Prometheus 表达式浏览器中以表格形式展示,或者作为数据源, HTTP API 的方式提供给外部系统使用。
注意:默认情况下,是以当前时间为基准点,来进行数据的获取操作。
表达式形式
官方文档: https://prometheus.io/docs/prometheus/latest/querying/basics/
PromQL 的查询操需要针对有限个时间序列上的样本数据进行,挑选出目标时间序列是构建表达式时最为关键的一步, 然后根据挑选出给定指标名称下的所有时间序列或部分时间序列的即时(当前)样本值或至过去某个时间范围内的样本值。
#即时数据,指定时间点的数据
[root@ubuntu2204 ~]#date -d @1600000000
2020年 09月 13日 星期日 20:26:40 CST
#查看2020年 09月 13日的数据

[root@prometheus ~]#curl --data 'query=prometheus_http_requests_total' --data 
time=1600000000 'http://10.0.0.100:9090/api/v1/query'
#范围数据,指定时间前1分钟的数据

[root@prometheus ~]#curl --data 'query=node_memory_MemFree_bytes{instance=~"10.0.0.
(101|102):9100"}[1m]' --data time=1600000000 'http://10.0.0.100:9090/api/v1/query'
#标量数据,利用scalar()函数将即时数据转换为标量

[root@prometheus ~]#curl --data 
'query=scalar(sum(node_memory_MemTotal_bytes{instance=~"10.0.0.(101|102):9100"}))' --
data time=1600000000 'http://10.0.0.100:9090/api/v1/query'
PromQL 运算
对于 PromQL 来说,它的操作符号主要有以下两类:
♣ 二元运算符   https://prometheus.io/docs/prometheus/latest/querying/operators/
♣ 聚合运算    https://prometheus.io/docs/prometheus/latest/querying/operators/
rate irate 函数
都表示变化速率,但有所不同。 一般 irate 函数的图像峰值变化大, rate 函数变化较为平缓。
rate函数=时间区间前后两个点的差 / 时间范围

4.定制开发Exporter

定制 Exporter 案例 : Python 实现
~ # apt update && apt install -y python3      #apt 安装 python3
~ # apt update && apt install -y python3-pip   # 安装 Python 包管理器,默认没有安装
#不安装虚拟环境软件
~# apt install -y python3-flask python3-prometheus-client
~ # pip3 config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple #  安装相关模块库
#安装虚拟环境软件
~# apt install python3-stevedore python3-virtualenvwrapper
#创建用户
~# useradd -m -s /bin/bash python
#准备目录
~# mkdir -p /data/venv
~# chown python.python /data/venv
#修改配置文件(可选)
~# su - python
~# vim .bashrc
force_color_prompt=yes #取消此行注释,清加颜色显示

#配置加速
~# mkdir ~/.pip
~# vim .pip/pip.conf 
[global] 
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install] 
trusted-host=pypi.douban.com
#配置虚拟软件
echo 'export WORKON_HOME=/data/venv' >> .bashrc
echo 'export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3' >> .bashrc
echo 'export VIRTUALENVWRAPPER_VIRTUALENV=/usr/local/bin/virtualenv' >> .bashrc
echo 'source /usr/local/bin/virtualenvwrapper.sh' >> .bashrc
source .bashrc

#注意:virtualenv 和 virtualenvwrapper.sh 的路径位置
#创建新的虚拟环境并自动进入
~# mkvirtualenv -p python3 flask_env
#进入已创建的虚拟环境
~# su - python
~# workon flask_env
#虚拟环境中安装相关模块库
~# pip install flask prometheus_client
~# pip list
范例: 定制 flask web 项目
#!/usr/bin/python3
"""
Flask应用监控指标脚本
功能:提供两个HTTP服务端口
- 8000端口:供Prometheus采集监控指标
- 8001端口:接收访问请求,每访问一次/metrics端点会使计数器加1
"""

# 导入所需模块
from prometheus_client import start_http_server, Counter, Summary
from flask import Flask, jsonify
from wsgiref.simple_server import make_server
import time

# 初始化Flask应用
app = Flask(__name__)

# 定义监控指标
# 1. 用于跟踪请求处理时间的摘要指标
REQUEST_TIME = Summary(
    'request_processing_seconds', 
    'Time spent processing request'
)

# 2. 用于计数总请求量的计数器指标
REQUEST_COUNTER = Counter(
    "request_count_total", 
    "Total request count of the host"
)

@app.route("/metrics")
@REQUEST_TIME.time()  # 记录该接口的处理时间
def metrics_endpoint():
    """
    处理8001端口的/metrics请求
    每次访问会使请求计数器加1,并返回成功响应
    """
    REQUEST_COUNTER.inc()  # 计数器递增1
    return jsonify({"return": "success OK!"})

if __name__ == "__main__":
    # 启动Prometheus指标暴露服务(8000端口)
    start_http_server(8000)
    print("Prometheus metrics server started on port 8000")
    
    # 启动Flask应用服务(8001端口,监听所有网络接口)
    httpd = make_server('0.0.0.0', 8001, app)
    print("Flask application started on port 8001")
    
    # 持续运行服务
    httpd.serve_forever()
当每访问一次链接 http://10.0.0.101:8001/metrics 时, 10.0.0.101:8000/metrics request_count_toal 值就会增加1
[root@ubuntu2204 ~] #while true;do curl 10.0.0.100:8001/metrics;sleep 0.$[RANDOM%10];done

5 Prometheus 标签管理

范例:添加主机标签

原来的标签
更改后的标签

①指标的生命周期

标签的两种形式:
私有标签:以"__*"样式存在,用于获取监控目标的默认元数据属性,比如__address__用于获取目标的地址, __scheme__用户获取目标的请求协议方法,__metrics_path__获取请求的url地址等。
普通标签:对个监控主机节点上的监控指标进行各种灵活的管理操作,常见的操作有,删除不必要|
敏感指标,添加、编辑或者修改指标的标签值或者标签格式。

②relabel_configs metric_relabel_configs

relabel_config metric_relabel_configs 这两个配置虽然在作用上类似,但是还是有本质上的区别的,这些区别体现在两个方面:执行顺序和数据处理上。
对比维度 relabel_configs metric_relabel_configs
执行顺序 在 scrape_configs 生效前执行 在 scrape_configs 生效后执行
作用对象 针对 target(采集目标)本身 针对 metric(监控指标数据)
数据处理 对采集目标的标签进行预处理(如过滤目标、修改目标标签等) 在 Prometheus 保存数据前对指标标签进行最终编辑,可过滤不需要的指标数据(直接丢弃不保存)
核心用途 调整采集目标的标签属性,决定哪些目标被采集 调整指标的标签属性,决定哪些指标被保存

③标签管理

对于一些全局性的标签,可以在 global 部分通过属性来设置,格式如下:
global:
 ...
  # 与外部系统通信时添加到任何时间序列或警报的标签
 external_labels:
   [ <labelname>: <labelvalue> ... ]
官方文档如下:
https://prometheus.io/docs/prometheus/latest/configuration/configuration/#relabel_config
https: //prometheus.io/docs/prometheus/latest/configuration/configuration/#metric_relabel_configs
relabel_config metric_relabel_configs 的使用格式基本上一致,常见配置如下

范例:
#示例:删除指标名node_network_receive开头的标签
metric_relabel_configs:
- source_labels: [__name__] 
 regex: 'node_network_receive.*'
 action: drop

#示例:替换
metric_relabel_configs:
- source_labels: 
 regex: '/.*'
 replacement: '123456'
 target_label: replace_id
范例:基于 source_labels 的值赋值给新的标签名
scrape_configs:
 ...
  - job_name: 'consul'
   honor_labels: true  #如果抓取的原有标签和Prometheus配置的标签冲突,保留原有标签,避免标签覆
盖
   consul_sd_configs:
      - server: 'consul-node1.wang.org:8500'
       services: []  #指定需要发现的service名称,默认为所有service,或者如下面两行指定只从
consul中加载特定的service
        #tags:       #可以过滤具有指定的tag的service
        #- "service"  
        #refresh_interval: 2m #刷新时间间隔,默认30s
      - server: 'consul-node2.wang.org:8500'  #添加其它两个节点实现冗余
      - server: 'consul-node3.wang.org:8500'  #添加其它两个节点实现冗余
   relabel_configs:
    - source_labels: ['__meta_consul_service']  #基于source_labels的值赋值给新的标签
consul_service
     target_label: 'consul_service'
   - source_labels: ['__meta_consul_dc']       #基于source_labels的值赋值给新的标签
datacenter
     target_label: 'datacenter'  
    - source_labels: ['__meta_consul_tags']     #基于source_labels的值赋值给新的标签app
     target_label: 'app'     
    - source_labels: ['__meta_consul_service']  #删除consul的service,此service是consul
内置,但并不提供metrics数据
     regex: "consul"
     action: drop

6.记录和告警规则

Prometheus 支持两种类型的规则: 1.记录规则    2.警报规则
#promtool check rules prometheus_rues_file.yml    规则语法检查
可以在 prometheus.yaml 配置文件中通过 rule_fies 属性进行导入即可,格式如下
rule_files:
 - "first_rules.yml"
 - "second_rules.yml"
 - "../rules/*.yml"
  
#注意: 如果用相对路径是指相对于prometheus.yml配置文件的路径
记录规则说明:https://prometheus.io/docs/prometheus/latest/configuration/recording_rules/

记录规则实现:vim /etc/prometheus/prometheus_record_rules.yml

groups:
  - name: myrules
    # 规则组说明:针对Flask应用的自定义监控指标规则
    rules:
      # 规则1:计算每次请求的平均处理时间
      - record: "request_process_per_time"
        expr: request_processing_seconds_sum{job="my_metric"} / request_processing_seconds_count{job="my_metric"}
        labels:
          app: "flask"       # 应用标识
          role: "web"        # 角色标识
      
      # 规则2:计算每分钟的请求数量
      - record: "request_count_per_minute"
        expr: increase(request_count_total{job="my_metric"}[1m])
        labels:
          app: "flask"       # 应用标识
          role: "web"        # 角色标识
       

检查rule和全局配置文件

#访问测试
[root@ubuntu2404 ~] #while true ;do curl 127.0.0.1:8001/metrics;sleep 0.$[RANDOM%10];done
# 登录到 prometheus web 界面,可以通过 request_prcess_per_time 指标查询我们想要的数据,效果如下:
范例:mysql记录规则
vim /etc/prometheus/rules/mysql_record_rules.yml
groups:
- name: mysqld_rules
 rules:
  # Record slave lag seconds for pre-computed timeseries that takes
  # `mysql_slave_status_sql_delay` into account
  - record: instance:mysql_slave_lag_seconds
   expr: mysql_slave_status_seconds_behind_master - mysql_slave_status_sql_delay

  # Record slave lag via heartbeat method
  - record: instance:mysql_heartbeat_lag_seconds
   expr: mysql_heartbeat_now_timestamp_seconds -
mysql_heartbeat_stored_timestamp_seconds

  - record: job:mysql_transactions:rate5m
   expr: sum without (command) (rate(mysql_global_status_commands_total{command=~"
(commit|rollback)"}[5m]))

①告警说明和 Alertmanager 部署

告警介绍官方文档: https://prometheus.io/docs/alerting/latest/overview/
告警组件
告警特性
https://prometheus.io/docs/alerting/latest/alertmanager/
Alertmanager 部署
具体部署略
可以通过访问 http://10.0.0.200:9093/ 来看 alertmanager 提供的 Web 界面
prometheus集成
方式1: 静态配置   vim /etc/prometheus/prometheus.yml
alerting:
 alertmanagers:
  - static_configs:
    - targets: ["10.0.0.201:9093"]

方式2:文件发现  vim /etc/prometheus/prometheus.yml

alerting:
 alertmanagers:
  - file_sd_configs:
    - "targets/alertmanager*.yaml"

vim /etc/prometheus/targets/alertmanager.yaml

- targets:
  - alert.wang.org:9093
 labels:
   app: alertmanager
   job: alertmanager
# promtool check config /etc/prometheus/conf/prometheus.yml   语法检查
# systemctl reload prometheus.service  重启服务,加载配置
# 建议配置 alertmanager 自身也被 Prometheus 监控
#方式1:静态配置
]# vim /usr/local/prometheus/conf/prometheus.yml
scrape_configs:
  - job_name: "alertmanager"
   static_configs:
      - targets: ["alertmanager.wang.org:9093"]

#方式2:文件发现
]# vim /usr/local/prometheus/conf/prometheus.yml
scrape_configs:
  - job_name: "alertmanager"
   file_sd_configs:
    - files:
      - targets/alertmanager.yaml
]# vim /usr/local/prometheus/conf/targets/alertmanager.yaml
- targets:
  - alert.wang.org:9093
 labels:
   app: alertmanager
   job: alertmanager  
Alertmanager 配置文件说明
 
官方文档: https://prometheus.io/docs/alerting/latest/configuration/
Alertmanager 通过 yml 格式的配置文件,Alertmanager 配置文件格式说明
# 配置文件总共定义了五个模块, global templates route receivers inhibit_rules

②Alertmanager 启用邮件告警

https://prometheus.io/docs/alerting/latest/configuration/#email_config
邮箱服务器开启smtp的授权码,每个邮箱开启授权码操作不同
QQ 邮箱开启邮件通知功能
网易邮箱开启邮件通知功能
范例: 163 实现邮件告警的配置文件
#当前QQ邮箱有异常,建议使用163的非加密形式
[root@ubuntu2404 ~]#cat /usr/local/alertmanager/conf/alertmanager.yml
global:
 resolve_timeout: 5m                        
 smtp_smarthost: 'smtp.163.com:25'           #基于全局块指定发件人信息,此处设为25,如果465
还需要添加tls相关配置
 smtp_from: 'lbtooth@163.com'
 smtp_auth_username: 'lbtooth@163.com'
 smtp_auth_password: 'xxxxxxxxxxxxxxxxxxxxxxxxx'
 smtp_hello: '163.com'
 smtp_require_tls: false        #启用tls安全,默认true,此处设为false
# 路由配置
route:
 group_by: ['alertname', 'cluster']
 group_wait: 10s
 group_interval: 10s
 repeat_interval: 10s  #此值不要过低,否则短期内会收到大量告警通知
 receiver: 'email'     #指定接收者名称
# 收信人员
receivers:
- name: 'email'
 email_configs:
  - to: 'root@xiaoming.com'
   send_resolved: true           #问题解决后也会发送恢复通知  

③告警规则

规则说明:https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/
Prometheus 告警规则: 各种告警规则都有(Node Exporter、MySQL、blackbox等
https://samber.github.io/awesome-prometheus-alerts/

④告警规则案例: 邮件告警

编写一个检查自定义 metrics 的接口的告警规则,在 prometheus 中我们可以借助于 up指标来获取对应的状态效果,查询语句如下:
up {job = "my_metric" } #注意:如果结果是 1 表示服务正常,否则表示该接口的服务出现了问题。
#确认包含rules目录中的yml文件
cat /usr/local/prometheus/conf/prometheus.yml
rule_files:
  - "../rules/*.yml"
#准备告警rule文件
vim /usr/local/prometheus/rules/prometheus_alert_rules.yml 
groups:
- name: flask_web
 rules:
  - alert: InstanceDown
   expr: up{job="my_metric"} == 0
    #expr: up == 0     #所有targets
    for: 1m
   labels:
     severity: 1
   annotations:
      #title: Instance Down    
     summary: "Instance {{ $labels.instance }} 停止工作"
     description: "{{ $labels.instance }} job {{ $labels.job }} 已经停止1m以上"
      
#属性解析:
- name: flask_web  #指定分组名称,在一个组中可以有多个 alert ,只要其中一个alert条件满足,就会触发
告警
{{ $labels.<labelname> }} 要插入触发元素的标签值
{{ $value }} 要插入触发元素的数值表达式值
#这里的$name 都是来源于模板文件中的定制内容,如果不需要定制的变动信息,可以直接写普通的字符串
#检查语法
promtool check rules prometheus_alert_rules.yml 
  
#重启prometheus服务
systemctl reload prometheus.service

验证: 停止自定义的 flask 服务,稍等 1 分钟后,查看告警效果。
等待时间超过 for 持续的标准后,就会改变告警的状态,效果如下
邮件告警效果
静默 silence 
如果想停止告警,可以用静默功能 ,在AlertManger 上指定告警的 silence

⑤定制模板案例

为了更好的显示效果 , 需要了解 html 相关技术 , 参考链接 https://www.w3school.com.cn/html/html_tables.asp
范例:邮件模板(不唯一)
vim /usr/local/alertmanager/tmpl/email_template.tmpl
{{ define "email.html" }}
{{- if gt (len .Alerts.Firing) 0 -}}
{{ range .Alerts }}
=========start==========<br>
告警程序: prometheus_alert <br>
告警级别: {{ .Labels.severity }} <br>
告警类型: {{ .Labels.alertname }} <br>
告警主机: {{ .Labels.instance }} <br>
告警主题: {{ .Annotations.summary }} <br>
告警详情: {{ .Annotations.description }} <br>
触发时间: {{ .StartsAt.Format "2006-01-02 15:04:05" }} <br>
=========end==========<br>
{{ end }}{{ end -}}
{{- if gt (len .Alerts.Resolved) 0 -}}
{{ range .Alerts }}
=========start==========<br>
告警程序: prometheus_alert <br>
告警级别: {{ .Labels.severity }} <br>
告警类型: {{ .Labels.alertname }} <br>
告警主机: {{ .Labels.instance }} <br>
告警主题: {{ .Annotations.summary }} <br>
告警详情: {{ .Annotations.description }} <br>
触发时间: {{ .StartsAt.Format "2006-01-02 15:04:05" }} <br>
恢复时间: {{ .EndsAt.Format "2006-01-02 15:04:05" }} <br>
=========end==========<br>
{{ end }}{{ end -}}
{{- end }}

应用模版

]# vim /usr/local/alertmanager/conf/alertmanager.yml
global:
...
templates:            #加下面两行加载模板文件
  - '../tmpl/*.tmpl'  #相对路径是相对于altermanager.yml文件的路径
...
# 收信人员
receivers:
- name: 'email'
 email_configs:
  - to: 'root@xiaoming.com'
   send_resolved: true
   headers: { Subject: "[WARN] 报警邮件"}   #添加此行,定制邮件标题
   html: '{{ template "test.html" . }}'    #添加此行,调用模板显示邮件正文
    #html: '{{ template "email.html" . }}'   #添加此行,调用模板显示邮件正文

然后再重启prometheus进行验证

⑥告警路由

上图所示: Alertmanager 中的第一个 Route 是根节点,每一个 match 都是子节点。
比如,我们之前定义的告警策略中,只有一个 route ,这意味着所有由 Prometheus 产生的告警在发送到Alertmanager之后都会通过名为 email receiver 接收。
注意 : 新版中使用指令 matchers 替换了 match match_re 指令
https://prometheus.io/docs/alerting/latest/configuration/#route
https://prometheus.io/docs/alerting/latest/configuration/#matcher
告警路由案例
#准备prometheus配置文件
grep -Ev '^$|^ *#' /usr/local/prometheus/conf/prometheus.yml
global:
 scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is 
every 1 minute.
 evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 
minute.
alerting:
 alertmanagers:
    - static_configs:
        - targets:
            - 10.0.0.100:9093  #指定alertmaanager地址
rule_files:
  - "../rules/*.yml"           #指定规则文件路径
scrape_configs:
  - job_name: "prometheus"
   static_configs:
      - targets: ["localhost:9090"]
  - job_name: 'node_exporter'
   static_configs:
    - targets: ['10.0.0.101:9100','10.0.0.102:9100','10.0.0.103:9100']
     labels: {app: 'k8s-node'}
  - job_name: 'my_metric'
   static_configs:
    - targets: ['10.0.0.101:8000']
     labels: {app: 'flask_web'}
#配置告警规则
vim /usr/local/prometheus/rules/prometheus_alert_route.yml
groups:
- name: flask_web
 rules:
  - alert: InstanceDown
   expr: up{job="my_metric"} == 0
    for: 1m
   labels:
     severity: critical
   annotations:
     summary: "Instance {{ $labels.instance }} 停止工作"
     description: "{{ $labels.instance }} job {{ $labels.job }} 已经停止1分钟以上"
     value: "{{$value}}"
- name: flask_QPS
 rules:
  - alert: InstanceQPSIsHight
   expr: increase(request_count_total{job="my_metric"}[1m]) > 500
5.5.2.2 定制路由分组
    for: 1m
   labels:
     severity: warning
   annotations:
     summary: "Instance {{ $labels.instance }} QPS 持续过高"
     description: "{{ $labels.instance }} job {{ $labels.job }} QPS 持续过高"
     value: "{{$value}}"
# 指定 flask_web 规则的 labels severity: critical
# 指定 flask_QPS 规则的 labels severity: warning
# 重启 prometheus 服务
systemctl reload prometheus.service
# 查看 prometheus 上的路由规则效果
定制路由分组
#指定路由分组
vim /usr/local/alertmanager/conf/alertmanager.yml
# 全局配置
global:
 resolve_timeout: 5m
 smtp_smarthost: 'smtp.qq.com:25'
 smtp_from: '123456@qq.com'
 smtp_auth_username: '123456@qq.com'
 smtp_auth_password: 'abefxqzcnxhqaebieb'
 smtp_hello: 'qq.com'
 smtp_require_tls: false
# 模板配置
templates:
  - '../tmpl/*.tmpl'
# 路由配置
#新版:使用指令matchers替换match和match_re,如下示例
route:
 group_by: ['instance', 'cluster']
 group_wait: 10s
 group_interval: 10s
 repeat_interval: 10s
 receiver: 'email'
 routes:
  - receiver: 'leader-team'
   matchers:
    - severity = "critical"
  - receiver: 'ops-team'
   matchers:
    - severity =~ "^(warning)$"
 #子路由  
  #- matchers
  # - severity = "critical"
  # - job =~ "mysql|java"
  # receiver: 'leader-team'
  # routes: #支持routes嵌套和分级
  # - matchers:
  #   - job =~ "mysql"
  #   receiver: 'dba-team'
  #- matchers
  # - severity =~ "warning"
  # - job = "node_exporter"
  # receiver: 'ops-team'    
  
# 收信人员
receivers:
- name: 'email'
 email_configs:
  - to: 'root@wangxiaochun.com'
   send_resolved: true
   html: '{{ template "test.html" . }}'
   headers: { Subject: "[WARN] 报警邮件"}
- name: 'leader-team'
 email_configs:
  - to: 'root@wangxiaochun.com'
   html: '{{ template "test.html" . }}'
   headers: { Subject: "[CRITICAL] 应用服务报警邮件"}
   send_resolved: true  #
- name: 'ops-team'
 email_configs:
  - to: 'root@xiaoming.com'
   html: '{{ template "test.html" . }}'
   headers: { Subject: "[WARNNING] QPS负载报警邮件"}
   send_resolved: true

#检查语法
amtool check-config /usr/local/alertmanager/conf/alertmanager.yml
systemctl reload alertmanager.service   # 服务生效

⑦ 告警抑制

案例: 启动抑制机制  
在alertmanager里面添加下面的代码
# 抑制措施                          
inhibit_rules: 
- source_match: 
   severity: critical     #被依赖的告警服务
 target_match:             
   severity: warning      #依赖的告警服务
 equal:
    - instance

#重启alertmanager服务
systemctl reload alertmanager.service
验证结果如下
# 关停服务后,查看效果    
# 结果显示:开启告警抑制之后,因为 critical 导致的 warning 事件就不再告警了,从而减少了告警风暴现象。
微信告警和钉钉告警略

7.Alertmanager 高可用

Gossip 谣言协议实现
https://yunlzheng.gitbook.io/prometheus-book/part-ii-prometheus-jin-jie/readmd/alertmanager-high-availability
Gossip 有两种实现方式分别为 Push-based Pull-based
Push-based 当集群中某一节点 A 完成一个工作后,随机的挑选其它节点 B 并向其发送相应的消息,节点 B 接收到消息后在重复完成相同的工作,直到传播到集群中的所有节点。
Pull-based 的实现中节点 A 会随机的向节点 B 发起询问是否有新的状态需要同步,如果有则返回。
搭建本地集群环境为了能够让Alertmanager 节点之间进行通讯,需要在 Alertmanager 启动时设置相应的参数。其中主要的参数包括:
--web .listen-address string       # 当前实例 Web 监听地址和端口 , 默认 9093 ,可以使用默认值
--cluster .listen-address string   # 当前实例集群服务监听地址 , 默认 9094 ,可使用默认值,集群必选
--cluster .peer value   # 后续集群实例在初始化时需要关联集群中的已有实例的服务地址 , 集群的后续节点必选
范例 : 同一个主机上 alertmanager 三个实例实现 Promthues Alertmanager HA 部署结构
#创建Alertmanager配置文件/etc/prometheus/alertmanager-ha.yml, 为了验证Alertmanager的集群
行为,这里在本地启动一个webhook服务用于打印Alertmanager发送的告警通知信息。
route:
 receiver: 'default-receiver'
receivers:
  - name: default-receiver
   webhook_configs:
    - url: 'http://127.0.0.1:5001/'
    
# 获取alertmanager提供的webhook示例,如果该目录下定义了main函数,go get会自动将其编译成可执行文件
go get github.com/prometheus/alertmanager/examples/webhook
export PATH=$GOPATH/bin:$PATH  # 设置环境变量指向GOPATH的bin目录
webhook  # 启动服务

#a1: 
alertmanager  --web.listen-address=":9093" --cluster.listen-address="127.0.0.1:8001"
--config.file=/etc/prometheus/alertmanager-ha.yml  --storage.path=/data/alertmanager/ 
--log.level=debug
#a2: 
alertmanager  --web.listen-address=":9094" --cluster.listen-address="127.0.0.1:8002"
--cluster.peer=127.0.0.1:8001 --config.file=/etc/prometheus/alertmanager-ha.yml  --
storage.path=/data/alertmanager2/ --log.level=debug
#a3: 
alertmanager  --web.listen-address=":9095" --cluster.listen-address="127.0.0.1:8003"
--cluster.peer=127.0.0.1:8001 --config.file=/etc/prometheus/alertmanager-ha.yml  --
storage.path=/data/alertmanager2/ --log.level=debug



#创建Promthues集群配置文件/etc/prometheus/prometheus-ha.yml,完整内容如下:
global:
 scrape_interval: 15s
 scrape_timeout: 10s
 evaluation_interval: 15s
rule_files:
  - /etc/prometheus/rules/*.rules
alerting:
 alertmanagers:
  - static_configs:
    - targets:
      - 127.0.0.1:9093
      - 127.0.0.1:9094
      - 127.0.0.1:9095
scrape_configs:
- job_name: prometheus
 static_configs:
  - targets:
    - localhost:9090
- job_name: 'node'
 static_configs:
  - targets: ['localhost:9100']
  
  
#同时定义告警规则文件/etc/prometheus/rules/hoststats-alert.rules,如下所示:
groups:
- name: hostStatsAlert
 rules:
  - alert: hostCpuUsageAlert
   expr: sum(avg without (cpu)(irate(node_cpu{mode!='idle'}[5m]))) by (instance) * 
100 > 50
    for: 1m
   labels:
     severity: page
   annotations:
     summary: "Instance {{ $labels.instance }} CPU usgae high"
     description: "{{ $labels.instance }} CPU usage above 50% (current value: {{ 
$value }})"
  - alert: hostMemUsageAlert
   expr: (node_memory_MemTotal - node_memory_MemAvailable)/node_memory_MemTotal * 
100 > 85
    for: 1m
   labels:
     severity: page
   annotations:
     summary: "Instance {{ $labels.instance }} MEM usgae high"
     description: "{{ $labels.instance }} MEM usage above 85% (current value: {{ 
$value }})"
      
#创建prometheus.procfile文件,创建两个Promthues节点,分别监听9090和9091端口:
#p1: 
prometheus --config.file=/etc/prometheus/prometheus-ha.yml --
storage.tsdb.path=/data/prometheus/ --web.listen-address="127.0.0.1:9090"
#p2: 
prometheus --config.file=/etc/prometheus/prometheus-ha.yml --
storage.tsdb.path=/data/prometheus2/ --web.listen-address="127.0.0.1:9091"
#node_exporter
node_exporter: node_exporter -web.listen-address="0.0.0.0:9100"
其它告警应用
https://github.com/feiyu563/PrometheusAlert
范例 : Docker 部署 prometheus alert
docker run -d \
-p 8080:8080 \
-e PA_LOGIN_USER=prometheusalert \
-e PA_LOGIN_PASSWORD=prometheusalert \
-e PA_TITLE=PrometheusAlert \
-e PA_OPEN_FEISHU=1 \
-e PA_OPEN_DINGDING=1 \
-e PA_OPEN_WEIXIN=1 \
feiyu563/prometheus-alert:latest

#浏览器访问,用户名/密码默认是prometheusalert/prometheusalert
http://prometheusalert.wang.org:8080

8.服务发现

对于小型的系统环境来说,通过 static_configs 指定各 Target 便能解决问题,这也是最简单的配置方法 , 我们只需要在配置文件中,将每个Targets 用一个网络端点( ip:port )进行标识;
- job_name: 'node_exporter'
   static_configs:
    - targets: ['10.0.0.101:9100']
对于中大型的系统环境或具有较强动态性的云计算环境来说,由于场景体量的因素,静态配置显然难以适用。
服务发现机制  https://prometheus.io/docs/prometheus/latest/configuration/configuration/
服务发现的原理
文件服务发现案例
#创建目标目录
mkdir /usr/local/prometheus/conf/targets
cd /usr/local/prometheus/conf/targets

#添加linux主机目标
ls /usr/local/prometheus/conf/targets/
prometheues-flask.yml prometheues-node.yml prometheues-server.yml

#创建prometheus的服务配置
cat prometheues-server.yml
- targets:
  - 10.0.0.101:9090
 labels:
   app: prometheus-server
   job: prometheus-server
    
cat prometheues-node.yml
- targets:
  - 10.0.0.101:9100
 labels:
   app: prometheus
   job: prometheus
- targets:
  - 10.0.0.104:9100
  - 10.0.0.105:9100
 labels:
   app: node-exporter
   job: node
cat prometheues-flask.yml 
- targets:
  - 10.0.0.101:8000
 labels:
   app: flask-web
   job: prometheus-flask
   
#修改prometheus的配置文件,让它自动加载文件中的节点信息
cd /usr/local/prometheus/conf
cp prometheus.yml{,.bak}

#编辑配置文件
#cat /usr/local/prometheus/conf/prometheus.yml(全局配置)
global:
 scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is 
every 1 minute.
 evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 
minute.
  # scrape_timeout is set to the global default (10s).
# Alertmanager configuration
alerting:
 alertmanagers:
    - static_configs:
        - targets:
rule_files:
scrape_configs:
  - job_name: "file_sd_prometheus"
   scrape_interval: 10s  #指定抓取数据的时间间隔
   file_sd_configs:
    - files:
      - targets/prometheues-server.yml
     refresh_interval: 10s  #指定重读文件的时间间隔,默认值5m
  - job_name: 'file_sd_node_exporter'
   file_sd_configs:
    - files:
      - targets/prometheues-node.yml
     refresh_interval: 10s
  - job_name: 'file_sd_flask_web'
   file_sd_configs:
    - files:
      - targets/prometheues-flask.yml
     refresh_interval: 10s

#配置文件语法检查
promtool check config prometheus.yml

#重启服务
systemctl reload prometheus.service

#稍等几秒钟,到浏览器中查看监控目标
#结果显示:所有的节点都添加完毕了,而且每个节点都有自己的标签信息

9.DNS 服务发现

参考资料https://prometheus.io/docs/prometheus/latest/configuration/configuration/#dns_sd_config
DNS 服务发现案例
部署DNS环境
#安装软件
apt update && apt -y install bind9 bind9utils bind9-doc bind9-host 
named -v

#查看部署软件
dpkg -L bind9 | grep named.conf
/etc/bind/named.conf
/etc/bind/named.conf.default-zones
/etc/bind/named.conf.local
/etc/bind/named.conf.options

#定制正向解析zone的配置
cat >> /etc/bind/named.conf.default-zones 
//定制网站主域名的zone配置
zone "wang.org" {
       type master;
       file "/etc/bind/wang.org.zone";
};

#定制主域名的zone文件
vim /etc/bind/wang.org.zone
;
; BIND reverse data file for local loopback interface
;
$TTL    604800
@       IN     SOA     ns.wang.org. admin.wang.org. (
                              1         ; Serial
                         604800         ; Refresh
                          86400         ; Retry
                        2419200         ; Expire
                         604800 )       ; Negative Cache TTL
;
       IN     NS     master
master IN     A       10.0.0.100
node1   IN     A       10.0.0.101
node2   IN     A       10.0.0.102
node3   IN     A       10.0.0.103
flask   IN     A       10.0.0.101

#检查配置文件
named-checkconf

#重启dns服务
rndc reload
systemctl restart named
systemctl status named

#配置prometheus服务器使用DNS域名服务器
vim /etc/netplan/01-netcfg.yaml
network:
 version: 2
 renderer: networkd
 ethernets:
   eth0:
     addresses:
      - 10.0.0.101/24
     gateway4: 10.0.0.2
     nameservers:
       search: [wang.org,wang.com]
       addresses: [10.0.0.100] #只保留当前的DNS服务器地址,别再加其它DNS服务器地址,否则DNS
解析有问题

#应用网络配置
netplan apply

#确认dns解析效果
dig node1.wang.org
host node1.wang.org
nslookup node1.wang.org
配置 DNS 服务支持 SRV 记录
#添加SRV记录
# vim /etc/bind/wang.org.zone
... ...
node1   IN     A       10.0.0.101
node2   IN     A       10.0.0.102
node3   IN     A       10.0.0.103
flask   IN     A       10.0.0.101  #只有A记录

#添加下面的SRV记录,对应上面的三条A记录
_prometheus._tcp.wang.org. 1H IN SRV 10 10 9100 node1.wang.org.
_prometheus._tcp.wang.org. 1H IN SRV 10 10 9100 node2.wang.org.
_prometheus._tcp.wang.org. 1H IN SRV 10 10 9100 node3.wang.org.

#检查配置文件
named-checkconf

#生效
rndc reload

#测试解析
dig srv _prometheus._tcp.wang.org
host -t srv _prometheus._tcp.wang.org
nslookup -q=srv _prometheus._tcp.wang.org
配置 Prometheus 使用 DNS
# vim /usr/local/prometheus/conf/prometheus.yml
... 
scrape_configs:
  - job_name: "prometheus"
   .......
    
#添加下面所有行
  - job_name: 'dns_sd_flask'             #实现单个主机定制的信息解析,也支持DNS或/etc/hosts
文件实现解析
   dns_sd_configs:
    - names: ['flask.wang.org']
     type: A                            #指定记录类型,默认SRV
     port: 8000                         #不是SRV时,需要指定Port号
     refresh_interval: 10s
      
  - job_name: 'dns_sd_node_exporter'          #实现批量主机解析
   dns_sd_configs:
    - names: ['_prometheus._tcp.wang.org']    #SRV记录必须通过DNS的实现
     refresh_interval: 10s                   #指定DNS资源记录的刷新间隔,默认30s
   relabel_configs:                          #生成新的标签service,值为_prometheus._tcp
    - source_labels: ['__meta_dns_name']
     regex:         '(.+?)\.wang\.org'
     target_label:  'service'
     replacement:   '$1'
      
#重启prometheus
promtool check config /usr/local/prometheus/conf/prometheus.yml
systemctl reload prometheus

验证结果

添加和删除 SRV 记录
#删除node2和添加node4对应的SRV和A记录
[root@prometheus ~]#cat /etc/bind/wang.org.zone
$TTL 1D
@ IN SOA master admin (
 1 ; serial
 1D ; refresh
 1H ; retry
 1W ; expire
 3H ) ; minimum
           NS   master
master         A       10.0.0.100         
node1   IN     A       10.0.0.101
node3   IN     A       10.0.0.103
node4   IN     A       10.0.0.104  #修改
flask   IN     A       10.0.0.101

_prometheus._tcp.wang.org. 1H IN SRV 10 10 9100 node1.wang.org.
_prometheus._tcp.wang.org. 1H IN SRV 10 10 9100 node3.wang.org.
_prometheus._tcp.wang.org. 1H IN SRV 10 10 9100 node4.wang.org. #修改

#注意:Ubuntu有DNS缓存,需要清除才能生效
[root@ubuntu2404 ~]#systemctl restart systemd-resolved.service
[root@prometheus ~]#rndc reload && netplan apply 
server reload successful

#确认结果
[root@prometheus ~]#host -t srv _prometheus._tcp.wang.org
_prometheus._tcp.wang.org has SRV record 10 10 9100 node1.wang.org.
_prometheus._tcp.wang.org has SRV record 10 10 9100 node3.wang.org.
_prometheus._tcp.wang.org has SRV record 10 10 9100 node4.wang.org.
确认是否自动发现生效

10.Consul 服务发现

 Docker 启动 Consul
docker pull consul:1.6.1 # 拉取指定版本
docker run -d -p 8500 :8500 --restart = always --name = consul consul:latest agent -server-bind = 10 .0.0.100 -client = 0 .0.0.0 -bootstrap-expect = 1 -ui
部署 Consul 集群
帮助
https://developer.hashicorp.com/consul/docs/agent/config/config-files
https://developer.hashicorp.com/consul/docs/agent/config/cli-flags
集群架构说明
https://developer.hashicorp.com/consul/docs/install/glossary
二进制部署 Consul 集群
# 启动第 1 个节点
[root@ubuntu2204 ~] #consul agent -bind=10.0.0.201 -client=0.0.0.0 -data-dir=/data/consul -node=node1 -ui -server -bootstrap
# 启动第 2 个节点
[root@ubuntu2204 ~] #consul agent -bind=10.0.0.202 -client=0.0.0.0 -data-dir=/data/consul -node=node2 -retry-join=10.0.0.201 -ui -server -bootstrap-expect 2
#启动第3个节点
[root@ubuntu2204 ~] #consul agent -bind=10.0.0.203 -client=0.0.0.0 -data-dir=/data/consul -node=node3 -retry-join=10.0.0.201 -ui -server -bootstrap-expect 2
http://consul.wang.org:8500
# 访问第一个有 -ui 功能的节点
其他的略

11 各种 Exporter

Exporter 官方文档: https://prometheus.io/docs/instrumenting/exporters/
Logo

码道开发者社区,聚焦华为云码道 CodeArts 代码智能体,沉淀 Agent、Skill、鸿蒙开发实战内容,供开发者查阅资料、交流技术、分享工程实践

更多推荐