1. 项目概述:为什么选择Prometheus+Grafana监控方案
在分布式系统和云原生架构成为主流的今天,传统的监控工具如Zabbix、Nagios已经难以满足动态环境下的监控需求。Prometheus作为CNCF毕业项目,凭借其多维数据模型、强大的查询语言和高效的时序数据库,已经成为云原生监控的事实标准。而Grafana作为可视化领域的标杆,其丰富的面板库和灵活的告警配置,让监控数据真正"活"起来。
这套组合方案特别适合以下场景:
- 需要监控Kubernetes集群及其上运行的容器化应用
- 对服务级别指标(SLI)有明确要求的微服务架构
- 需要自定义业务指标的场景(如电商的订单成功率、API响应延迟等)
- 混合云环境下需要统一监控视图的企业
我在多个生产环境中部署这套系统时发现,相比传统方案,它具有三个显著优势:
- 安装配置简单,一个二进制文件即可启动核心服务
- 资源占用低,单节点可处理百万级时间序列
- 生态丰富,官方和社区提供了数百种Exporter
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 环境准备与基础配置
2.1 系统要求与依赖检查
推荐使用Ubuntu 20.04 LTS或CentOS 7+作为基础系统。在开始前需要确认:
bash复制# 检查内核版本(建议3.10+)
uname -r
# 检查内存(建议4GB+)
free -h
# 检查存储(建议50GB+剩余空间)
df -h
关键依赖包括:
- systemd(用于服务管理)
- curl/wget(下载安装包)
- tar(解压工具)
- 防火墙配置(开放相关端口)
重要提示:生产环境建议禁用Swap,避免内存压力时监控数据写入性能下降。执行
sudo swapoff -a并注释掉/etc/fstab中的swap行。
2.2 网络与安全配置
默认需要开放的端口:
- Prometheus: 9090/tcp
- Grafana: 3000/tcp
- Node Exporter: 9100/tcp
使用firewalld配置示例:
bash复制sudo firewall-cmd --permanent --add-port=9090/tcp
sudo firewall-cmd --permanent --add-port=3000/tcp
sudo firewall-cmd --reload
对于生产环境,建议:
- 通过Nginx配置HTTPS反向代理
- 启用Grafana的LDAP/SSO集成
- 配置Prometheus的TLS加密通信
3. Prometheus核心组件部署
3.1 二进制安装与配置
从官网下载最新稳定版(当前为2.37.0):
bash复制wget https://github.com/prometheus/prometheus/releases/download/v2.37.0/prometheus-2.37.0.linux-amd64.tar.gz
tar xvfz prometheus-*.tar.gz
cd prometheus-2.37.0.linux-amd64
创建专用用户和系统服务:
bash复制sudo useradd --no-create-home --shell /bin/false prometheus
sudo mkdir /etc/prometheus /var/lib/prometheus
sudo cp prometheus promtool /usr/local/bin/
sudo cp -r consoles console_libraries /etc/prometheus/
配置文件示例(/etc/prometheus/prometheus.yml):
yaml复制global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_configs:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
- job_name: 'node'
static_configs:
- targets: ['localhost:9100']
3.2 系统服务集成
创建systemd服务文件(/etc/systemd/system/prometheus.service):
ini复制[Unit]
Description=Prometheus
Wants=network-online.target
After=network-online.target
[Service]
User=prometheus
Group=prometheus
ExecStart=/usr/local/bin/prometheus \
--config.file=/etc/prometheus/prometheus.yml \
--storage.tsdb.path=/var/lib/prometheus \
--web.console.templates=/etc/prometheus/consoles \
--web.console.libraries=/etc/prometheus/console_libraries
Restart=always
[Install]
WantedBy=multi-user.target
启动并验证:
bash复制sudo systemctl daemon-reload
sudo systemctl start prometheus
sudo systemctl enable prometheus
# 检查状态
curl http://localhost:9090/-/healthy
3.3 数据存储优化
Prometheus的TSDB存储有几个关键参数需要关注:
--storage.tsdb.retention.time:数据保留周期(默认15d)--storage.tsdb.retention.size:存储空间限额--storage.tsdb.wal-compression:启用WAL压缩
对于生产环境建议:
bash复制ExecStart=/usr/local/bin/prometheus \
--config.file=/etc/prometheus/prometheus.yml \
--storage.tsdb.path=/var/lib/prometheus \
--storage.tsdb.retention.time=30d \
--storage.tsdb.retention.size=100GB \
--storage.tsdb.wal-compression
4. Grafana部署与集成
4.1 安装与初始配置
Ubuntu下安装最新版:
bash复制sudo apt-get install -y adduser libfontconfig1
wget https://dl.grafana.com/oss/release/grafana-9.0.5.linux-amd64.tar.gz
tar -zxvf grafana-9.0.5.linux-amd64.tar.gz
sudo mv grafana-9.0.5 /usr/share/grafana
sudo useradd --no-create-home --shell /bin/false grafana
sudo mkdir /var/lib/grafana
sudo chown grafana:grafana /var/lib/grafana
系统服务配置(/etc/systemd/system/grafana.service):
ini复制[Unit]
Description=Grafana
After=network.target
[Service]
User=grafana
Group=grafana
ExecStart=/usr/share/grafana/bin/grafana-server \
--config=/etc/grafana/grafana.ini \
--homepath=/usr/share/grafana \
--packaging=tar \
cfg:default.paths.logs=/var/log/grafana \
cfg:default.paths.data=/var/lib/grafana \
cfg:default.paths.plugins=/var/lib/grafana/plugins \
cfg:default.paths.provisioning=/etc/grafana/provisioning
Restart=on-failure
[Install]
WantedBy=multi-user.target
4.2 数据源配置
首次登录后(默认admin/admin),通过配置文件添加Prometheus数据源(/etc/grafana/provisioning/datasources/prometheus.yaml):
yaml复制apiVersion: 1
datasources:
- name: Prometheus
type: prometheus
access: proxy
url: http://localhost:9090
isDefault: true
editable: false
jsonData:
timeInterval: "15s"
httpMethod: "POST"
4.3 仪表板导入
推荐使用官方仪表板库:
- Node Exporter Full:ID 1860
- Prometheus 2.0 Stats:ID 3662
- Kubernetes Cluster:ID 315
导入方法:
bash复制# 使用grafana-cli安装仪表板
sudo grafana-cli plugins install grafana-piechart-panel
sudo systemctl restart grafana
5. 监控目标扩展配置
5.1 Node Exporter部署
基础系统指标采集:
bash复制wget https://github.com/prometheus/node_exporter/releases/download/v1.3.1/node_exporter-1.3.1.linux-amd64.tar.gz
tar xvfz node_exporter-*.tar.gz
sudo cp node_exporter-1.3.1.linux-amd64/node_exporter /usr/local/bin/
创建专用服务(/etc/systemd/system/node_exporter.service):
ini复制[Unit]
Description=Node Exporter
After=network.target
[Service]
User=node_exporter
Group=node_exporter
ExecStart=/usr/local/bin/node_exporter \
--collector.systemd \
--collector.processes \
--collector.tcpstat
Restart=always
[Install]
WantedBy=multi-user.target
5.2 黑盒监控配置
在prometheus.yml中添加:
yaml复制 - job_name: 'blackbox'
metrics_path: /probe
params:
module: [http_2xx]
static_configs:
- targets:
- http://example.com
- https://api.service:8443/health
relabel_configs:
- source_labels: [__address__]
target_label: __param_target
- source_labels: [__param_target]
target_label: instance
- target_label: __address__
replacement: blackbox_exporter:9115
6. 告警管理实战
6.1 Alertmanager配置
安装Alertmanager:
bash复制wget https://github.com/prometheus/alertmanager/releases/download/v0.24.0/alertmanager-0.24.0.linux-amd64.tar.gz
tar xvfz alertmanager-*.tar.gz
sudo cp alertmanager-0.24.0.linux-amd64/alertmanager /usr/local/bin/
sudo cp alertmanager-0.24.0.linux-amd64/amtool /usr/local/bin/
配置示例(/etc/alertmanager/alertmanager.yml):
yaml复制route:
group_by: ['alertname']
group_wait: 30s
group_interval: 5m
repeat_interval: 4h
receiver: 'web.hook'
receivers:
- name: 'web.hook'
webhook_configs:
- url: 'http://127.0.0.1:5001/'
6.2 Prometheus告警规则
定义规则文件(/etc/prometheus/rules/node_alerts.yml):
yaml复制groups:
- name: node_alerts
rules:
- alert: HighMemoryUsage
expr: (node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes) / node_memory_MemTotal_bytes * 100 > 90
for: 5m
labels:
severity: critical
annotations:
summary: "High memory usage on {{ $labels.instance }}"
description: "Memory usage is {{ $value }}%"
在prometheus.yml中启用:
yaml复制rule_files:
- /etc/prometheus/rules/*.yml
7. 性能调优与问题排查
7.1 资源限制配置
对于Prometheus的systemd服务添加资源限制:
ini复制[Service]
...
MemoryLimit=8G
CPUQuota=200%
LimitNOFILE=65536
Grafana的内存配置(/etc/grafana/grafana.ini):
ini复制[grafana_net]
...
[server]
http_port = 3000
enforce_domain = true
root_url = %(protocol)s://%(domain)s:%(http_port)s/
router_logging = false
[log]
level = warn
[paths]
data = /var/lib/grafana
7.2 常见问题处理
问题1:Prometheus存储增长过快
解决方案:
bash复制# 检查时间序列数量
curl -s http://localhost:9090/api/v1/status/tsdb | jq '.stats.numSeries'
# 启用块压缩
--storage.tsdb.max-block-duration=2h --storage.tsdb.min-block-duration=2h
问题2:Grafana面板加载慢
优化措施:
- 增加查询时间范围限制
- 使用Recording Rules预计算指标
- 启用Grafana的查询缓存
问题3:Alertmanager不发送告警
检查步骤:
bash复制# 检查静默状态
amtool silence
# 测试告警发送
amtool alert --alertmanager.url=http://localhost:9093 add node=test severity=critical
8. 生产环境最佳实践
8.1 高可用部署方案
推荐架构:
code复制 +-------------+
| Load Balancer |
+------+------+
|
+--------------------+--------------------+
| | |
+-------+------+ +--------+-------+ +-------+------+
| Prometheus A | | Prometheus B | | Alertmanager |
+-------+------+ +--------+-------+ +-------+------+
| | |
+--------------------+--------------------+
|
+------+------+
| Thanos |
+-------------+
关键配置:
- 两个Prometheus实例配置相同的采集任务
- 使用remote_write将数据同步到Thanos
- Alertmanager集群模式部署
8.2 监控Kubernetes集群
使用Prometheus Operator部署:
bash复制helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm install prometheus prometheus-community/kube-prometheus-stack \
--namespace monitoring \
--set prometheus.prometheusSpec.serviceMonitorSelectorNilUsesHelmValues=false
关键Exporter:
- kube-state-metrics:集群资源状态
- cadvisor:容器指标
- kubelet:节点资源
8.3 备份策略
Prometheus数据备份方案:
bash复制# 定时快照备份
curl -XPOST http://localhost:9090/api/v1/admin/tsdb/snapshot
# 备份到S3
aws s3 sync /var/lib/prometheus s3://your-bucket/prometheus-data/
Grafana配置备份:
bash复制# 导出所有仪表板
sudo sqlite3 /var/lib/grafana/grafana.db .dump > grafana_backup.sql
# 备份插件
tar czvf grafana_plugins_backup.tar.gz /var/lib/grafana/plugins/
