Prometheus 监控:完整配置与最佳实践
使用Prometheus建立强大的基础设施监控系统
Prometheus 已成为监控云原生应用程序和基础设施的实际标准,提供指标收集、查询和与可视化工具的集成。

什么是 Prometheus?
Prometheus 是一个开源的监控和告警工具包,最初于 2012 年由 SoundCloud 开发,现在是 Cloud Native Computing Foundation (CNCF) 的毕业项目。它专为动态云环境中的可靠性和可扩展性而设计,使其成为监控微服务、容器和 Kubernetes 集群的首选解决方案。
主要功能
时间序列数据库:Prometheus 将所有数据存储为时间序列,通过指标名称和键值对(标签)进行标识,从而实现灵活且强大的查询能力。
拉取模型:与传统的推送模型不同,Prometheus 主动从配置的目标中定期拉取指标,使其更加可靠且易于配置。
PromQL 查询语言:一种强大的函数式查询语言,允许您实时切片和分析指标数据,进行聚合、转换和复杂计算。
服务发现:通过各种机制(包括 Kubernetes、Consul、EC2 和静态配置)自动发现监控目标。
无外部依赖:Prometheus 作为一个单个二进制文件运行,无需任何外部依赖,简化了部署并减少了操作复杂性。
内置告警:AlertManager 处理来自 Prometheus 的告警,提供去重、分组和路由到通知渠道(如电子邮件、PagerDuty 或 Slack)的功能。
架构概述
了解 Prometheus 架构对于有效部署至关重要。主要组件包括:
- Prometheus 服务器:拉取并存储指标,评估规则并提供查询
- 客户端库:为应用程序代码提供指标暴露
- 导出器:将第三方系统桥接到 Prometheus 格式
- AlertManager:处理告警和通知
- Pushgateway:接受无法被拉取的短生命周期任务的指标
典型的数据流:应用程序暴露指标端点 → Prometheus 拉取这些端点 → 数据存储在时间序列数据库中 → PromQL 查询检索并分析数据 → 基于规则生成告警 → AlertManager 处理并路由通知。
在部署基础设施于 Ubuntu 24.04 时,Prometheus 提供了全面监控的绝佳基础。
在 Ubuntu 上安装 Prometheus
让我们逐步介绍如何在 Linux 系统上安装 Prometheus。我们将使用 Ubuntu 作为示例,但其他发行版的流程类似。
下载和安装
首先,为 Prometheus 创建一个专用用户:
sudo useradd --no-create-home --shell /bin/false prometheus
下载最新的 Prometheus 发布版本:
cd /tmp
wget https://github.com/prometheus/prometheus/releases/download/v2.48.0/prometheus-2.48.0.linux-amd64.tar.gz
tar xvf prometheus-2.48.0.linux-amd64.tar.gz
cd prometheus-2.48.0.linux-amd64
复制二进制文件并创建目录:
sudo cp prometheus /usr/local/bin/
sudo cp promtool /usr/local/bin/
sudo chown prometheus:prometheus /usr/local/bin/prometheus
sudo chown prometheus:prometheus /usr/local/bin/promtool
sudo mkdir /etc/prometheus
sudo mkdir /var/lib/prometheus
sudo chown prometheus:prometheus /etc/prometheus
sudo chown prometheus:prometheus /var/lib/prometheus
sudo cp -r consoles /etc/prometheus
sudo cp -r console_libraries /etc/prometheus
sudo cp prometheus.yml /etc/prometheus/prometheus.yml
sudo chown -R prometheus:prometheus /etc/prometheus
有关 Ubuntu 的包管理,请参考我们的全面 Ubuntu 包管理指南。
配置 Prometheus
编辑 /etc/prometheus/prometheus.yml:
global:
scrape_interval: 15s
evaluation_interval: 15s
alerting:
alertmanagers:
- static_configs:
- targets: ['localhost:9093']
rule_files:
- 'alert_rules.yml'
scrape_configs:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
- job_name: 'node_exporter'
static_configs:
- targets: ['localhost:9100']
创建 Systemd 服务
创建 /etc/systemd/system/prometheus.service:
[Unit]
Description=Prometheus
Wants=network-online.target
After=network-online.target
[Service]
User=prometheus
Group=prometheus
Type=simple
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 \
--storage.tsdb.retention.time=30d
[Install]
WantedBy=multi-user.target
启动并启用 Prometheus:
sudo systemctl daemon-reload
sudo systemctl start prometheus
sudo systemctl enable prometheus
sudo systemctl status prometheus
通过 http://localhost:9090 访问 Prometheus 的 Web 界面。
设置 Node Exporter
Node Exporter 用于暴露 Linux 系统的硬件和操作系统指标。安装它以监控您的服务器:
cd /tmp
wget https://github.com/prometheus/node_exporter/releases/download/v1.7.0/node_exporter-1.7.0.linux-amd64.tar.gz
tar xvf node_exporter-1.7.0.linux-amd64.tar.gz
sudo cp node_exporter-1.7.0.linux-amd64/node_exporter /usr/local/bin/
sudo chown prometheus:prometheus /usr/local/bin/node_exporter
创建 systemd 服务 /etc/systemd/system/node_exporter.service:
[Unit]
Description=Node Exporter
After=network.target
[Service]
User=prometheus
Group=prometheus
Type=simple
ExecStart=/usr/local/bin/node_exporter
[Install]
WantedBy=multi-user.target
启动 Node Exporter:
sudo systemctl daemon-reload
sudo systemctl start node_exporter
sudo systemctl enable node_exporter
Node Exporter 现在在端口 9100 上暴露指标。
了解 PromQL
PromQL(Prometheus 查询语言)是查询 Prometheus 数据的核心。以下是重要的查询模式:
基本查询
选择某个指标的所有时间序列:
node_cpu_seconds_total
按标签过滤:
node_cpu_seconds_total{mode="idle"}
多个标签过滤:
node_cpu_seconds_total{mode="idle",cpu="0"}
时间向量和聚合
计算时间范围内的速率:
rate(node_cpu_seconds_total{mode="idle"}[5m])
对所有 CPU 求和:
sum(rate(node_cpu_seconds_total{mode="idle"}[5m]))
按标签分组:
sum by (mode) (rate(node_cpu_seconds_total[5m]))
实用示例
CPU 使用百分比:
100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)
内存使用:
(node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes) / node_memory_MemTotal_bytes * 100
磁盘使用:
(node_filesystem_size_bytes - node_filesystem_avail_bytes) / node_filesystem_size_bytes * 100
网络流量速率:
rate(node_network_receive_bytes_total[5m])
Docker 部署
在 Docker 容器中运行 Prometheus 提供了灵活性和更易于管理:
创建 docker-compose.yml:
version: '3.8'
services:
prometheus:
image: prom/prometheus:latest
container_name: prometheus
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
- prometheus_data:/prometheus
command:
- '--config.file=/etc/prometheus/prometheus.yml'
- '--storage.tsdb.path=/prometheus'
- '--storage.tsdb.retention.time=30d'
ports:
- "9090:9090"
restart: unless-stopped
node_exporter:
image: prom/node-exporter:latest
container_name: node_exporter
command:
- '--path.rootfs=/host'
volumes:
- '/:/host:ro,rslave'
ports:
- "9100:9100"
restart: unless-stopped
alertmanager:
image: prom/alertmanager:latest
container_name: alertmanager
volumes:
- ./alertmanager.yml:/etc/alertmanager/alertmanager.yml
- alertmanager_data:/alertmanager
ports:
- "9093:9093"
restart: unless-stopped
volumes:
prometheus_data:
alertmanager_data:
启动堆栈:
docker-compose up -d
Kubernetes 监控
Prometheus 在监控 Kubernetes 集群 方面表现出色。kube-prometheus-stack Helm chart 提供了一个完整的监控解决方案。
使用 Helm 安装:
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update
helm install prometheus prometheus-community/kube-prometheus-stack
这将安装:
- Prometheus Operator
- Prometheus 实例
- AlertManager
- Grafana
- Node Exporter
- kube-state-metrics
- 预配置的仪表板和告警
访问 Grafana:
kubectl port-forward svc/prometheus-grafana 3000:80
默认凭据:admin/prom-operator
对于各种 Kubernetes 发行版,部署过程类似,只需对平台特定功能进行小幅调整。
设置告警
AlertManager 处理由 Prometheus 发送的告警。配置告警规则和通知渠道。
告警规则
创建 /etc/prometheus/alert_rules.yml:
groups:
- name: system_alerts
interval: 30s
rules:
- alert: HighCPUUsage
expr: 100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 80
for: 5m
labels:
severity: warning
annotations:
summary: "实例 {{ $labels.instance }} 的 CPU 使用率过高"
description: "CPU 使用率超过 80%(当前值:{{ $value }}%)"
- alert: HighMemoryUsage
expr: (node_memory_MemTotal_bytes - node_memory_MemAvailable_bytes) / node_memory_MemTotal_bytes * 100 > 85
for: 5m
labels:
severity: warning
annotations:
summary: "实例 {{ $labels.instance }} 的内存使用率过高"
description: "内存使用率超过 85%(当前值:{{ $value }}%)"
- alert: DiskSpaceLow
expr: (node_filesystem_avail_bytes / node_filesystem_size_bytes) * 100 < 15
for: 10m
labels:
severity: critical
annotations:
summary: "{{ $labels.instance }} 的磁盘空间不足"
description: "{{ $labels.mountpoint }} 的可用磁盘空间低于 15%"
- alert: InstanceDown
expr: up == 0
for: 2m
labels:
severity: critical
annotations:
summary: "实例 {{ $labels.instance }} 已关闭"
description: "{{ $labels.job }} 实例 {{ $labels.instance }} 已关闭超过 2 分钟"
AlertManager 配置
创建 /etc/prometheus/alertmanager.yml:
global:
resolve_timeout: 5m
smtp_smarthost: 'smtp.gmail.com:587'
smtp_from: 'alerts@example.com'
smtp_auth_username: 'alerts@example.com'
smtp_auth_password: 'your-password'
route:
group_by: ['alertname', 'cluster', 'service']
group_wait: 10s
group_interval: 10s
repeat_interval: 12h
receiver: 'team-email'
routes:
- match:
severity: critical
receiver: 'team-pagerduty'
- match:
severity: warning
receiver: 'team-slack'
receivers:
- name: 'team-email'
email_configs:
- to: 'team@example.com'
headers:
Subject: '{{ .GroupLabels.alertname }}: {{ .Status | toUpper }}'
- name: 'team-slack'
slack_configs:
- api_url: 'https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK'
channel: '#alerts'
title: '告警: {{ .GroupLabels.alertname }}'
text: '{{ range .Alerts }}{{ .Annotations.description }}{{ end }}'
- name: 'team-pagerduty'
pagerduty_configs:
- service_key: 'your-pagerduty-key'
与 Grafana 集成
虽然 Prometheus 有一个基本的 Web 界面,Grafana 提供了更强大的可视化功能,可以创建全面的仪表板。
添加 Prometheus 作为数据源
- 打开 Grafana 并导航到 配置 → 数据源
- 点击 “添加数据源”
- 选择 “Prometheus”
- 设置 URL 为
http://localhost:9090(或您的 Prometheus 服务器) - 点击 “保存并测试”
流行的仪表板 ID
从 grafana.com 导入预构建的仪表板:
- Node Exporter 全面仪表板(ID: 1860):全面的 Linux 指标
- Kubernetes 集群监控(ID: 7249):K8s 概览
- Docker 容器监控(ID: 193):容器指标
- Prometheus 内部指标(ID: 2):Prometheus 自身指标
创建自定义仪表板
使用 PromQL 查询创建面板:
{
"title": "CPU 使用率",
"targets": [{
"expr": "100 - (avg(rate(node_cpu_seconds_total{mode=\"idle\"}[5m])) * 100)"
}]
}
流行的导出器
使用专用导出器扩展 Prometheus 监控:
Blackbox Exporter
通过 HTTP、HTTPS、DNS、TCP 和 ICMP 探测端点:
scrape_configs:
- job_name: 'blackbox'
metrics_path: /probe
params:
module: [http_2xx]
static_configs:
- targets:
- https://example.com
- https://api.example.com
relabel_configs:
- source_labels: [__address__]
target_label: __param_target
- source_labels: [__param_target]
target_label: instance
- target_label: __address__
replacement: localhost:9115
数据库导出器
- mysqld_exporter:MySQL/MariaDB 指标
- postgres_exporter:PostgreSQL 指标
- mongodb_exporter:MongoDB 指标
- redis_exporter:Redis 指标
应用程序导出器
- nginx_exporter:NGINX Web 服务器指标
- apache_exporter:Apache HTTP 服务器指标
- haproxy_exporter:HAProxy 负载均衡器指标
云导出器
- cloudwatch_exporter:AWS CloudWatch 指标
- stackdriver_exporter:Google Cloud 指标
- azure_exporter:Azure Monitor 指标
最佳实践
数据保留
根据您的需求配置适当的数据保留时间:
--storage.tsdb.retention.time=30d
--storage.tsdb.retention.size=50GB
记录规则
预计算频繁查询的表达式:
groups:
- name: example_rules
interval: 30s
rules:
- record: job:node_cpu_utilization:avg
expr: 100 - (avg by (job) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)
标签管理
- 保持标签基数低
- 使用一致的命名约定
- 避免高基数标签(用户 ID、时间戳)
安全
- 启用身份验证和 HTTPS
- 限制对 Prometheus API 的访问
- 在 Kubernetes 中使用网络策略
- 对敏感指标实施 RBAC
高可用性
- 运行多个 Prometheus 实例
- 使用 Thanos 或 Cortex 进行长期存储
- 对分层设置实施联邦
常见问题排查
高内存使用
- 减少抓取频率
- 缩短保留期
- 优化 PromQL 查询
- 实施记录规则
缺失指标
- 检查
/targets中的目标状态 - 验证网络连接性
- 验证抓取配置
- 检查导出器日志
查询缓慢
- 对复杂聚合使用记录规则
- 优化标签过滤器
- 减少时间范围
- 如果使用远程存储,添加索引
性能优化
查询优化
# 不佳:高基数
sum(rate(http_requests_total[5m]))
# 佳:按相关标签分组
sum by (status, method) (rate(http_requests_total[5m]))
资源限制
对于 Kubernetes 部署:
resources:
requests:
memory: "2Gi"
cpu: "1000m"
limits:
memory: "4Gi"
cpu: "2000m"
结论
Prometheus 提供了一个强大且可扩展的监控解决方案,适用于现代基础设施。其拉取架构、强大的查询语言和广泛的导出器生态系统使其成为从裸机服务器到复杂 Kubernetes 集群的监控的理想选择。
通过将 Prometheus 与 Grafana 进行可视化以及 AlertManager 进行通知相结合,您可以创建一个能够处理企业级监控需求的全面可观测性平台。活跃的社区和 CNCF 的支持确保了持续的开发和支持。
从基本的指标收集开始,逐步为您的特定服务添加导出器,并根据实际经验优化告警规则。Prometheus 随着您的基础设施扩展,从单服务器部署到多数据中心监控架构。
相关资源
- 如何安装 Ubuntu 24.04 及有用工具
- Ubuntu 包管理:APT 和 dpkg 命令速查表
- 在 Ubuntu 上安装和使用 Grafana:完整指南
- Kubernetes 命令速查表
- Kubernetes 发行版 - kubeadm、k3s、MicroK8s、Minikube、Talos Linux 和 RKE2 的概述
- Docker 命令速查表