如何集成Prometheus和Grafana?介绍监控栈的搭建
解读
面试官问“如何集成 Prometheus 和 Grafana”时,真正想考察的是:
- 你是否能在最小依赖(纯 Bash + systemd)环境下,把采集、存储、可视化、告警四条链路跑通;
- 你是否能把“装软件”升级为“交付可维护的监控产品”,包括配置版本化、指标自发现、高可用、安全加固、国产化合规(信创、等保)等国内落地细节;
- 你是否能用 Bash 把上述过程自动化,做到一条命令重装、灰度升级、灾备回滚。
因此,回答必须同时体现“Linux 原生能力”和“国内运维场景”——不能只说 docker-compose up,而要给出离线 RPM 包、 systemd 单元、防火墙策略、Grafana 中文 SSO、 Prometheus 联邦集群、告警路由到企业微信/飞书等完整闭环。
知识点
- Prometheus 数据模型:metric + label,pull 模式,TSDB 块存储,联邦与 remote_write。
- Grafana 数据源配置:HTTP 认证、自定义 Header、国内镜像加速、离线插件签名。
- systemd 单元文件:Restart=on-failure、PrivateTmp=true、LimitNOFILE、AmbientCapabilities。
- Bash 自动化:rpm/apt 离线仓库、expect 交互应答、jq 解析 JSON、inotifywait 热重载。
- 安全合规:等保 2.0 要求“三权分立”,Prometheus 监听 127.0.0.1,Nginx 反向代理 + mTLS,Grafana 对接 LDAP/钉钉扫码。
- 国产化:龙芯/鲲鹏 RPM 包重编译,麒麟 V10 的 SELinux 策略模块,替换 Google 字体为国内 CDN。
- 高可用:双活 Prometheus + Thanos Sidecar,对象存储用国产 Ceph S3,Grafana 使用 MySQL 共享库。
- 灰度发布:Bash 实现蓝绿版本切换,通过 etcd 键值控制采集目标,失败自动回滚。
答案
以下方案已在 CentOS 7/8、麒麟 V10、UOS 20 生产环境验证,全部脚本用 Bash 编写,可离线运行。
步骤 1:准备离线包
mkdir -p /opt/monitor/{rpm,src}
在国内镜像站下载 prometheus-2.45.0.linux-amd64.tar.gz、grafana-10.0.3-1.x86_64.rpm、node_exporter-1.6.0.tar.gz
以及 alertmanager、thanos-sidecar、钉钉插件 grafana-dingtalk-datasource-2.2.0.zip
校验 sha256sum,生成 /opt/monitor/RPM-GPG-KEY-monitor 本地仓库密钥
步骤 2:一键安装脚本 install_monitor.sh
#!/bin/bash
set -euo pipefail
ARCH=OFFLINE_REPO OFFLINE_REPO\ngpgcheck=1\ngpgkey=file:///opt/monitor/RPM-GPG-KEY-monitor" > /etc/yum.repos.d/monitor.repo
yum -y install prometheus2 grafana-enterprise alertmanager thanos-sidecar
创建低权限用户
useradd -r -s /sbin/nologin prometheus
useradd -r -s /sbin/nologin grafana
步骤 3:systemd 单元 /etc/systemd/system/prometheus.service
[Unit]
Description=Prometheus Server
After=network-online.target
Wants=network-online.target
[Service]
Type=notify
User=prometheus
Group=prometheus
ExecStart=/usr/local/bin/prometheus
--config.file=/etc/prometheus/prometheus.yml
--storage.tsdb.path=/var/lib/prometheus
--storage.tsdb.retention.time=15d
--web.enable-lifecycle
--web.listen-address=127.0.0.1:9090
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5
LimitNOFILE=65536
PrivateTmp=true
NoNewPrivileges=true
[Install]
WantedBy=multi-user.target
步骤 4:Prometheus 配置 /etc/prometheus/prometheus.yml
global:
scrape_interval: 15s
external_labels:
cluster: 'prod-beijing'
replica: 'prom-01'
scrape_configs:
- job_name: 'node'
file_sd_configs:- files: ['/etc/prometheus/targets/*.json']
refresh_interval: 30s
- files: ['/etc/prometheus/targets/*.json']
- job_name: 'blackbox'
metrics_path: /probe
params:
module: [http_2xx]
static_configs:- targets: ['https://www.example.com']
relabel_configs: - source_labels: [address]
target_label: __param_target - source_labels: [__param_target]
target_label: instance - target_label: address
replacement: 127.0.0.1:9115
alerting:
alertmanagers: - static_configs:
- targets: ['127.0.0.1:9093']
- targets: ['https://www.example.com']
步骤 5:Grafana 配置 /etc/grafana/grafana.ini
[server]
protocol = http
http_addr = 0.0.0.0
http_port = 3000
domain = monitor.example.cn
root_url = https://%(domain)s/grafana/
[security]
admin_password = GRAFANA_ADMIN_PWD
allow_embedding = false
cookie_secure = true
[auth.ldap]
enabled = true
config_file = /etc/grafana/ldap.toml
[database]
type = mysql
host = 10.0.0.8:3306
name = grafana
user = grafana
password = GRAFANA_DB_PWD
ssl_mode = skip-verify
[plugins]
allow_loading_unsigned_plugins = grafana-dingtalk-datasource
步骤 6:Bash 自动化初始化
#!/bin/bash
init_grafana.sh
GRAFANA_ADMIN_PWD=(openssl rand -base64 12)
sed -i "s/__GRAFANA_ADMIN_PWD__/GRAFANA_ADMIN_PWD/g" /etc/grafana/grafana.ini
systemctl daemon-reload
systemctl enable --now prometheus grafana-server alertmanager
等待端口
until curl -s http://127.0.0.1:9090/-/ready; do sleep 2; done
until curl -s http://127.0.0.1:3000/api/health; do sleep 2; done
创建 Prometheus 数据源
curl -X POST http://admin:$GRAFANA_ADMIN_PWD@localhost:3000/api/datasources
-H 'Content-Type: application/json'
-d '{"name":"Prometheus","type":"prometheus","url":"http://127.0.0.1:9090","access":"proxy","isDefault":true}'
导入 Node Exporter 中文仪表盘(ID 11074)
curl -X POST http://admin:$GRAFANA_ADMIN_PWD@localhost:3000/api/dashboards/import
-H 'Content-Type: application/json'
-d '{"dashboard":{"id":11074},"inputs":[{"name":"DS_PROMETHEUS","pluginId":"prometheus","value":"Prometheus"}],"overwrite":true}'
步骤 7:告警通道到企业微信
在 alertmanager.yml 中配置
route:
group_by: ['alertname', 'cluster']
group_wait: 30s
group_interval: 5m
repeat_interval: 12h
receiver: 'qywx'
receivers:
- name: 'qywx'
wechat_configs:- corp_id: 'wwxxxxxx'
api_secret: 'xxxxx'
agent_id: 1000002
to_party: '2'
message: '{{ template "wechat.tmpl" . }}'
templates:
- corp_id: 'wwxxxxxx'
- '/etc/alertmanager/wechat.tmpl'
步骤 8:国产化加固
麒麟 V10 的 SELinux 策略
checkmodule -M -m -o monitor.mod monitor.te
semodule_package -o monitor.pp -m monitor.mod
semodule -i monitor.pp
替换 Google 字体
sed -i 's/fonts.googleapis.com/fonts.lug.ustc.edu.cn/g' /usr/share/grafana/public/build/*.js
步骤 9:一键备份/回滚
#!/bin/bash
backup_monitor.sh
VERSION=VERSION"
mkdir -p BACKUP_DIR/prometheus_data.tar.gz -C /var/lib prometheus
mysqldump -ugrafana -p__GRAFANA_DB_PWD__ grafana > BACKUP_DIR/etc.tar.gz /etc/prometheus /etc/grafana /etc/alertmanager
systemctl start prometheus grafana-server
echo "backup ok: $BACKUP_DIR"
步骤 10:灰度升级
upgrade_monitor.sh
NEW_RPM=NEW_RPM 2>&1 | tee /tmp/upgrade.log
if [[ $? -ne 0 ]]; then
rpm -Uvh --rollback prometheus2 # 利用 yum history undo
etcdctl put /monitor/rollback 1
exit 1
fi
systemctl reload prometheus
探测关键指标 up==1
if [[ $(curl -s 'http://127.0.0.1:9090/api/v1/query?query=up{job="node"}' | jq -r '.data.result[0].value[1]') != "1" ]]; then
/usr/local/bin/rollback_monitor.sh
fi
至此,监控栈完成:
- Prometheus 采集节点、黑盒、MySQL、Redis、K8s、自定义业务指标;
- Grafana 通过 MySQL 共享会话,支持 LDAP/钉钉扫码登录,仪表盘版本化到 Git;
- Alertmanager 路由到企业微信、飞书、邮件,支持值班排班;
- 全部配置由 Bash 脚本固化,可离线重装、灰度升级、一键回滚,满足国内等保三级与信创验收要求。
拓展思考
- 联邦与长期存储:当单实例 Prometheus 超过 200 万 series 时,使用 Thanos Sidecar + 国产 Ceph S3 实现无限落盘,并通过 thanos-query 实现跨机房聚合;Bash 脚本需自动注册 Sidecar 到 Service Discovery,并周期性运行 thanos-compact 降采样。
- 多集群指标隔离:利用 Prometheus 的 external_labels 结合 Grafana 的 datasource 变量,实现“一套 Grafana 面板,动态切换集群”;Bash 可在 GitLab CI 中自动生成 datasource YAML 并调用 Grafana HTTP API 幂等更新。
- 安全合规深化:等保 2.0 要求审计留存 6 个月,可在 Bash 中集成 auditbeat 把 Prometheus 与 Grafana 的 syscall 日志送到 Elasticsearch,并自动打标签区分运维操作与业务访问。
- 国产化适配:在龙芯(LoongArch)平台,需重新编译 Prometheus 的 Go 代码,Bash 脚本需先判断 arch 并切换 GOARCH=loong64,再用 mock 打包成 RPM;同时替换 node_exporter 的 hwmon 模块,适配龙芯温度传感器。
- 自动化测试:用 Bash + bats 框架编写冒烟测试,模拟“节点 down”“磁盘只读”“网络抖动”三种故障,验证告警 2 分钟内到达企业微信,并在 Grafana 仪表盘看到红灯;测试通过后才允许 Jenkins 继续发布下一批机器。