Prometheus + Grafana 监控环境搭建完全指南

Prometheus + Grafana 监控环境搭建完全指南

Someone Lv5

Prometheus + Grafana 监控环境搭建完全指南

在服务器运维中,监控系统是不可或缺的基础设施。本文将从零开始,详细介绍如何在一台 Linux 服务器上搭建 Prometheus + Grafana 监控栈,实现对服务器性能指标的可视化监控。

一、Prometheus 简介与架构

Prometheus 是一款开源的系统监控和告警工具包,由 SoundCloud 开发并于 2012 年开源,现为 CNCF(云原生计算基金会)的毕业项目。

核心架构

Prometheus 的核心架构包含以下组件:

  • Prometheus Server:负责数据采集、存储和查询
  • Exporters:将各种服务的指标数据暴露为 Prometheus 可抓取的格式
  • Grafana:负责数据可视化的仪表板
  • Alertmanager:负责告警路由与通知

Prometheus 采用拉取(Pull)模型主动从各目标端点抓取监控数据,这是一个与传统推送模型方案截然不同的设计理念。

优势特点

相比其他监控方案(如 Zabbix、Nagios),Prometheus 的优势在于:

  • 多维数据模型,支持灵活的时间序列查询
  • 强大的 PromQL 查询语言
  • 高效的内存存储和文件存储
  • 自动发现能力(支持 Kubernetes、Consul、文件等发现方式)
  • 轻量级部署,不依赖外部存储

二、安装 Prometheus Server

支持多种安装方式,本文覆盖两种最常用的方法。

方式一:官方二进制安装(推荐)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# 1. 创建用户和目录
sudo useradd --no-create-home --shell /usr/sbin/nologin prometheus
sudo mkdir -p /etc/prometheus /var/lib/prometheus

# 2. 下载 Prometheus(请替换为最新版本号)
cd /tmp
wget https://github.com/prometheus/prometheus/releases/download/v2.54.0/prometheus-2.54.0.linux-amd64.tar.gz
tar -xzf prometheus-2.54.0.linux-amd64.tar.gz
cd prometheus-2.54.0.linux-amd64

# 3. 将二进制文件复制到系统路径
sudo cp prometheus promtool /usr/local/bin/
sudo cp -r consoles console_libraries /etc/prometheus/

# 4. 创建配置文件
sudo tee /etc/prometheus/prometheus.yml > /dev/null << 'EOF'
# my global config
global:
scrape_interval: 15s # 全局抓取间隔
evaluation_interval: 15s # 规则评估间隔

# Alertmanager 配置
alerting:
alertmanagers:
- static_configs:
- targets: []

# 规则文件(告警规则和记录规则)
rule_files:
# - "first_rules.yml"

# 抓取配置
scrape_configs:
# Prometheus 自身指标
- job_name: "prometheus"
static_configs:
- targets: ["localhost:9090"]
EOF

# 5. 设置权限
sudo chown -R prometheus:prometheus /etc/prometheus /var/lib/prometheus

# 6. 创建 systemd 服务
sudo tee /etc/systemd/system/prometheus.service > /dev/null << 'EOF'
[Unit]
Description=Prometheus
Documentation=https://prometheus.io/docs/introduction/overview/
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

[Install]
WantedBy=multi-user.target
EOF

# 7. 启动服务
sudo systemctl daemon-reload
sudo systemctl enable prometheus
sudo systemctl start prometheus
sudo systemctl status prometheus

安装完成后,访问 http://服务器IP:9090,如果看到 Prometheus Web UI,说明安装成功。

方式二:Docker 安装(极简)

1
2
3
4
5
6
7
8
9
10
11
# 创建数据目录
mkdir -p /opt/prometheus/data

# 运行 Prometheus 容器
docker run -d \
--name prometheus \
--restart unless-stopped \
-p 9090:9090 \
-v /opt/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml \
-v /opt/prometheus/data:/prometheus \
prom/prometheus:v2.54.0

三、部署 Node Exporter

Node Exporter 是 Prometheus 官方的硬件和操作系统指标采集器,支持 Linux/Unix 系统。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 1. 创建用户
sudo useradd --no-create-home --shell /usr/sbin/nologin node_exporter

# 2. 下载并安装
cd /tmp
wget https://github.com/prometheus/node_exporter/releases/download/v1.8.0/node_exporter-1.8.0.linux-amd64.tar.gz
tar -xzf node_exporter-1.8.0.linux-amd64.tar.gz
cd node_exporter-1.8.0.linux-amd64
sudo cp node_exporter /usr/local/bin/

# 3. 创建 systemd 服务
sudo tee /etc/systemd/system/node_exporter.service > /dev/null << 'EOF'
[Unit]
Description=Node Exporter
Documentation=https://prometheus.io/docs/guides/node-exporter/
Wants=network-online.target
After=network-online.target

[Service]
User=node_exporter
Group=node_exporter
Type=simple
ExecStart=/usr/local/bin/node_exporter \
--web.listen-address=:9100 \
--path.rootfs=/

[Install]
WantedBy=multi-user.target
EOF

# 4. 启动
sudo systemctl daemon-reload
sudo systemctl enable node_exporter
sudo systemctl start node_exporter

在 Prometheus 中添加 Node Exporter 作为目标

编辑 /etc/prometheus/prometheus.yml,在 scrape_configs 末尾添加:

1
2
3
- job_name: "node"
static_configs:
- targets: ["localhost:9100"]

重启 Prometheus 使配置生效:

1
sudo systemctl restart prometheus

四、安装 Grafana

Grafana 是业界最流行的开源数据可视化平台,支持 Prometheus 作为数据源。

通过 APT 安装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 1. 添加 Grafana 官方源
sudo apt-get install -y software-properties-common
sudo add-apt-repository "deb https://packages.grafana.net/oss/deb stable main"

# 2. 导入 GPG 密钥
wget -q -O - https://packages.grafana.net/gpg.key | sudo apt-key add -

# 3. 安装
sudo apt-get update
sudo apt-get install -y grafana

# 4. 启动
sudo systemctl daemon-reload
sudo systemctl enable grafana-server
sudo systemctl start grafana-server

通过 Docker 安装

1
2
3
4
5
6
docker run -d \
--name grafana \
--restart unless-stopped \
-p 3000:3000 \
-v /opt/grafana:/var/lib/grafana \
grafana/grafana:latest

配置 Grafana

  1. 访问 http://服务器IP:3000,默认用户名和密码均为 admin
  2. 首次登录会提示修改密码
  3. 进入 Configuration → Data Sources → Add data source
  4. 选择 Prometheus
  5. 在 URL 字段填写 http://localhost:9090(如果 Grafana 与 Prometheus 在同一台服务器)
  6. 点击 Save & Test,看到 “Data source is working” 即为成功

导入仪表板

Grafana 拥有丰富的社区仪表板模板,可直接导入:

  1. 点击左侧 +Import
  2. 在 “Import via grafana.com” 输入仪表板 ID:
    • Node Exporter Full(ID: 1860):最全面的 Linux 系统监控仪表板
    • Node Exporter Server Metrics(ID: 11074):简洁版本
  3. 选择数据源为 Prometheus
  4. 点击 Import
仪表板名称ID监控指标
Node Exporter Full1860CPU、内存、磁盘、网络、负载、进程
Prometheus 2.0 Stats3662Prometheus 自身性能指标
1 Node Overview for Prometheus11074简洁版单节点概览
Blackbox Exporter7587HTTP/HTTPS/ICMP 探测
Docker Monitoring179Docker 容器监控

五、添加更多 Exporters

常见 Exporter 列表

除了 Node Exporter,Prometheus 生态提供了大量的 Exporter:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Blackbox Exporter(内外网探测)
docker run -d --name blackbox_exporter --restart unless-stopped -p 9115:9115 prom/blackbox-exporter:latest

# MySQL Exporter
docker run -d --name mysql_exporter --restart unless-stopped -p 9104:9104 \
-e DATA_SOURCE_NAME="user:password@(localhost:3306)/" \
prom/mysqld-exporter:latest

# Nginx Exporter(需启用 stub_status)
docker run -d --name nginx_exporter --restart unless-stopped -p 9113:9113 \
nginx/nginx-prometheus-exporter:latest \
-nginx.scrape-uri=http://localhost:80/nginx_status

# Redis Exporter
docker run -d --name redis_exporter --restart unless-stopped -p 9121:9121 \
oliver006/redis_exporter:latest -redis.addr redis://localhost:6379

Prometheus 配置示例(多 Exporter)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
scrape_configs:
- job_name: "prometheus"
static_configs:
- targets: ["localhost:9090"]

- job_name: "node"
static_configs:
- targets:
- "192.168.1.10:9100"
- "192.168.1.11:9100"
- "192.168.1.12:9100"

- job_name: "mysql"
static_configs:
- targets: ["localhost:9104"]

- job_name: "nginx"
static_configs:
- targets: ["localhost:9113"]

- job_name: "redis"
static_configs:
- targets: ["localhost:9121"]

- job_name: "blackbox_http"
metrics_path: /probe
params:
module: [http_2xx]
static_configs:
- targets:
- https://example.com
- https://example.org
relabel_configs:
- source_labels: [__address__]
target_label: __param_target
- source_labels: [__param_target]
target_label: instance
- target_label: __address__
replacement: localhost:9115

六、配置告警规则

创建告警规则文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
sudo tee /etc/prometheus/alert-rules.yml > /dev/null << 'EOF'
groups:
- name: node_alerts
rules:
# CPU 使用率过高
- 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 usage is over 80%"
description: "CPU usage on {{ $labels.instance }} is at {{ $value }}%"

# 磁盘空间不足
- alert: DiskSpaceLow
expr: (node_filesystem_avail_bytes{mountpoint="/",fstype!~"tmpfs|overlay"} / node_filesystem_size_bytes{mountpoint="/",fstype!~"tmpfs|overlay"}) * 100 < 10
for: 5m
labels:
severity: critical
annotations:
summary: "{{ $labels.instance }} disk space is below 10%"
description: "Disk on {{ $labels.instance }} mount {{ $labels.mountpoint }} has {{ $value }}% free"

# 内存不足
- alert: HighMemoryUsage
expr: (1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)) * 100 > 90
for: 5m
labels:
severity: warning
annotations:
summary: "{{ $labels.instance }} memory usage is over 90%"

# 实例宕机
- alert: InstanceDown
expr: up == 0
for: 1m
labels:
severity: critical
annotations:
summary: "Instance {{ $labels.instance }} is down"
description: "{{ $labels.instance }} of job {{ $labels.job }} has been down for more than 1 minute"
EOF

然后在 prometheus.yml 中引用该规则文件:

1
2
rule_files:
- "alert-rules.yml"

重启 Prometheus 后,在 Web UI 的 Alerts 页面可以查看告警状态。

七、常用 PromQL 查询

PromQL 是 Prometheus 的查询语言,以下是一些运维中常用的查询:

查询用途PromQL
CPU 使用率100 - (avg by(instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)
内存使用率(1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)) * 100
磁盘使用率(node_filesystem_avail_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"}) * 100
磁盘 IO 负载rate(node_disk_io_time_seconds_total[5m])
网络流量(入站)rate(node_network_receive_bytes_total[5m]) * 8
网络流量(出站)rate(node_network_transmit_bytes_total[5m]) * 8
系统负载node_load15
运行时间time() - node_boot_time_seconds
进程数量node_procs_running

八、安全加固建议

在生产环境中使用 Prometheus 和 Grafana 时,安全不容忽视:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 1. 为 Grafana 配置反向代理(Nginx)+ HTTPS
# 2. 为 Prometheus 启用 basic_auth
# 3. 使用防火墙限制端口访问

# Prometheus basic_auth 配置示例
# 先生成密码哈希
sudo apt-get install -y apache2-utils
htpasswd -c /etc/prometheus/web.yml admin

# 在 prometheus.yml 中启用 basic_auth 或使用 --web.config.file 参数
# 启动命令增加: --web.config.file=/etc/prometheus/web.yml

# 防火墙规则
sudo ufw allow 22/tcp # SSH
sudo ufw allow 80/tcp # HTTP(如使用反向代理)
sudo ufw allow 443/tcp # HTTPS
sudo ufw allow 3000/tcp # Grafana(仅限内网或通过反向代理)
sudo ufw deny 9090/tcp # Prometheus API 不应公网暴露
sudo ufw deny 9100/tcp # Node Exporter 不应公网暴露

九、验证与测试

安装完成后,按以下步骤验证监控栈是否正常工作:

1
2
3
4
5
6
7
8
9
10
11
12
13
# 1. 检查 Prometheus 是否运行
curl http://localhost:9090/-/ready
# 返回 "Prometheus is Ready" 即为正常

# 2. 检查 Node Exporter
curl http://localhost:9100/metrics | head -20

# 3. 检查 Prometheus 是否抓到数据(在 Web UI 执行 PromQL)
curl 'http://localhost:9090/api/v1/query?query=up'

# 4. 检查 Grafana
curl http://localhost:3000/api/health
# 返回 {"msg":"Grafana is running"} 即为正常

在 Prometheus Web UI 的 Status → Targets 页面,可以看到所有配置的抓取目标及其健康状态。所有目标显示为 UP 状态,说明配置正确。

十、总结

本文详细介绍了从零搭建 Prometheus + Grafana 监控栈的完整流程,包括:

  1. Prometheus Server 的两种安装方式(二进制和 Docker)
  2. Node Exporter 部署与系统指标采集
  3. Grafana 安装配置与仪表板导入
  4. 多种 Exporter 的扩展部署
  5. 告警规则 的编写与配置
  6. PromQL 常用查询语句
  7. 安全加固 最佳实践

这套监控栈轻量、易扩展、社区活跃,足以应对从小型服务器到大型集群的各种监控需求。后续还可以接入 Alertmanager 实现多通道告警通知(邮件、钉钉、Slack、企业微信等),以及部署 Prometheus 联邦集群来监控跨区域的多数据中心。


本文由AI辅助生成,内容仅供参考

  • 标题: Prometheus + Grafana 监控环境搭建完全指南
  • 作者: Someone
  • 创建于 : 2026-06-09 13:00:00
  • 更新于 : 2026-06-18 08:39:57
  • 链接: https://demo-blog.qusite.cn/2026-06-09-prometheus-grafana-guide/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。