0

Prometheus+Grafana监控部署完整教程:从安装到可视化告警的实战指南

2026.05.22 | youres | 19次围观

Prometheus+Grafana监控部署完整教程:从安装到可视化告警的实战指南

一套好用的监控体系,是运维工程师的"眼睛"。没有监控,服务器CPU飙到100%你不知道,磁盘满了你不知道,服务挂了你还是不知道——等用户投诉过来,已经晚了。

在开源监控领域,Prometheus + Grafana 这对组合几乎是事实标准。Prometheus负责采集和存储指标数据,Grafana负责把数据变成好看的图表和告警。两套工具都是开源的,社区活跃,文档齐全,生产环境经过大量验证。

本文从零开始,手把手教你把这套监控体系跑起来。不废话,直接上实战。

一、Prometheus架构与核心概念

Prometheus最初由SoundCloud开发,后来捐给了CNCF(云原生计算基金会),和Kubernetes是"同门师兄弟"。它的核心设计思想很清晰:

  • 拉模式(Pull Model):Prometheus主动去抓取(scrape)各个目标暴露的指标数据,而不是各个目标主动推送。这样中心端可以统一控制采集频率和超时,架构更简单。
  • 时间序列数据库(TSDB):采集到的指标按时间戳存储,支持高效的时序查询。
  • 多维数据模型:每个指标可以带多个标签(label),比如cpu_usage{host="web01",env="prod"},查询时可以按标签灵活过滤和聚合。
  • PromQL查询语言:专为时序数据设计的查询语言,支持聚合、率计算、预测等高级操作。

Prometheus的核心组件:

  • Prometheus Server:核心服务,负责采集、存储、查询
  • Exporter:运行在被监控目标上的代理,暴露HTTP指标接口(比如Node Exporter暴露主机CPU、内存、磁盘指标)
  • Pushgateway:用于短生命周期任务的指标推送(可选)
  • Alertmanager:接收Prometheus发送的告警,去重、分组、路由到邮件/钉钉/Slack等渠道
  • Grafana:可视化层,把指标数据变成图表和仪表盘

二、Grafana简介与优势

Grafana是一个可视化平台,本身不采集数据,它负责把各种数据源(Prometheus、MySQL、Elasticsearch、Loki等)的数据变成漂亮的仪表盘。

为什么选Grafana而不是只用Prometheus自带的Web UI?

  • 仪表盘颜值高:图表类型丰富,配色专业,支持热力图、状态面板、直方图等高级可视化
  • 数据源广泛:一个Grafana可以接多个Prometheus集群,也可以同时接MySQL、Loki(日志)、Tempo(追踪),实现可观测性三大支柱的统一展示
  • 权限管理完善:支持团队、文件夹权限隔离,适合多团队共用
  • 告警功能强:Grafana 8.0之后内置了统一的告警引擎,可以直接在Grafana里配置告警规则,不依赖Alertmanager也能工作
  • 社区仪表盘丰富:Grafana官方仪表盘市场有上万套现成的,导入即用,不用自己从头画图表

三、环境准备与前置条件

演示环境用Ubuntu 22.04(CentOS/RHEL同理,包名和防火墙命令略有差异)。需要两台机器:

  • 监控服务器:运行Prometheus + Grafana,建议2核4G起步
  • 被监控服务器:运行Node Exporter,采集主机指标

前置条件:

# 放行端口(生产环境用安全组/iptables规则代替直接关闭防火墙)
# Ubuntu
sudo ufw allow 9090/tcp   # Prometheus
sudo ufw allow 3000/tcp   # Grafana
sudo ufw allow 9100/tcp   # Node Exporter
# CentOS
sudo firewall-cmd --permanent --add-port=9090/tcp
sudo firewall-cmd --permanent --add-port=3000/tcp
sudo firewall-cmd --permanent --add-port=9100/tcp
sudo firewall-cmd --reload

# 安装基础工具
sudo apt update && sudo apt install -y wget curl  # Ubuntu/Debian
# 或
sudo yum install -y wget curl  # CentOS/RHEL

四、Prometheus安装与配置

4.1 创建prometheus系统用户

sudo useradd --no-create-home --shell /bin/false prometheus

4.2 下载并安装Prometheus

# 查看最新版本:https://prometheus.io/download/
cd /tmp
wget https://github.com/prometheus/prometheus/releases/download/v2.53.0/prometheus-2.53.0.linux-amd64.tar.gz
tar -xvf prometheus-2.53.0.linux-amd64.tar.gz
cd prometheus-2.53.0.linux-amd64

sudo cp prometheus /usr/local/bin/
sudo cp promtool /usr/local/bin/
prometheus --version  # 验证安装成功

4.3 创建配置文件目录

sudo mkdir -p /etc/prometheus
sudo mkdir -p /var/lib/prometheus
sudo cp -r consoles /etc/prometheus/
sudo cp -r console_libraries /etc/prometheus/
sudo cp prometheus.yml /etc/prometheus/

4.4 配置prometheus.yml

编辑 /etc/prometheus/prometheus.yml

global:
  scrape_interval: 15s      # 每15秒采集一次
  evaluation_interval: 15s  # 每15秒评估一次告警规则

scrape_configs:
  - job_name: "prometheus"
    static_configs:
      - targets: ["localhost:9090"]  # Prometheus自监控

  # 后续添加Node Exporter目标(先注释,等Node Exporter装好再启用)
  # - job_name: "node"
  #   static_configs:
  #     - targets: ["被监控机器IP:9100"]

4.5 创建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

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable prometheus
sudo systemctl start prometheus
sudo systemctl status prometheus  # 确认Running

浏览器访问 http://监控服务器IP:9090,看到Prometheus Web UI说明安装成功。在Status → Targets页面可以看到prometheus任务状态为UP。

五、Node Exporter安装(采集主机指标)

被监控服务器上安装Node Exporter,它负责采集CPU、内存、磁盘、网络等主机指标,并通过HTTP接口暴露给Prometheus抓取:

# 创建用户
sudo useradd --no-create-home --shell /bin/false node_exporter

# 下载
cd /tmp
wget https://github.com/prometheus/node_exporter/releases/download/v1.8.0/node_exporter-1.8.0.linux-amd64.tar.gz
tar -xvf node_exporter-1.8.0.linux-amd64.tar.gz

# 安装二进制
sudo cp node_exporter-1.8.0.linux-amd64/node_exporter /usr/local/bin/
node_exporter --version

创建systemd服务 /etc/systemd/system/node_exporter.service

[Unit]
Description=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

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable node_exporter
sudo systemctl start node_exporter
sudo systemctl status node_exporter

验证:访问 http://被监控服务器IP:9100/metrics,能看到满屏的指标数据说明正常。

5.1 把Node Exporter加入Prometheus采集配置

回到监控服务器,编辑 /etc/prometheus/prometheus.yml,在 scrape_configs 下追加:

  - job_name: "node"
    static_configs:
      - targets: ["被监控服务器IP:9100"]
sudo systemctl restart prometheus

在Prometheus Web UI的"Status → Targets"页面,能看到node任务状态为UP,说明采集正常。

六、Grafana安装与初始化

6.1 安装Grafana(Ubuntu/Debian)

sudo apt-get install -y apt-transport-https software-properties-common
wget -q -O - https://packages.grafana.com/gpg.key | sudo apt-key add -
echo "deb https://packages.grafana.com/oss/deb stable main" | sudo tee /etc/apt/sources.list.d/grafana.list
sudo apt-get update
sudo apt-get install grafana

CentOS/RHEL用这个:

sudo tee /etc/yum.repos.d/grafana.repo << EOF
[grafana]
name=grafana
baseurl=https://packages.grafana.com/oss/rpm
repo_gpgcheck=1
enabled=1
gpgcheck=1
gpgkey=https://packages.grafana.com/gpg.key
sslverify=1
sslcacert=/etc/pki/tls/certs/ca-bundle.crt
EOF
sudo yum install grafana

6.2 启动Grafana

sudo systemctl enable grafana-server
sudo systemctl start grafana-server
sudo systemctl status grafana-server

浏览器访问 http://监控服务器IP:3000,默认账号密码 admin/admin,首次登录强制修改密码。

七、配置Prometheus数据源

登录Grafana后,把Prometheus接进来:

  1. 左侧菜单 → ConnectionsData SourcesAdd data source
  2. 选择 Prometheus
  3. URL 填写 http://localhost:9090(Grafana和Prometheus同一台机器)
  4. 滚动到底部,点击 Save & Test,显示"Data source is working"说明配置正确

八、导入仪表盘与可视化

最快捷的方式是导入社区现成的Node Exporter仪表盘,不用自己画图表:

  1. 左侧菜单 → DashboardsNewImport
  2. Import via dashboard ID 输入框填入 1860(Node Exporter Full,最流行的主机监控仪表盘,下载量超过百万)
  3. 点击 Load,选择刚才配置的Prometheus数据源
  4. 点击 Import,瞬间得到一个包含CPU、内存、磁盘、网络、负载、温度等所有核心指标的完整仪表盘

常用仪表盘ID参考:

  • 1860:Node Exporter Full(主机监控,必装,覆盖最全)
  • 11074:Node Exporter for Prometheus Dashboard(另一个常用版本,更简洁)
  • 3662:Prometheus 2.0 Overview(Prometheus自身监控)

九、配置告警规则

9.1 在Prometheus中配置告警规则

创建规则文件 /etc/prometheus/alerts.yml

groups:
  - name: 主机告警
    rules:
      - alert: 主机CPU使用率过高
        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使用率超过80%"
          description: "当前值: {{ $value }}%"

      - alert: 主机内存使用率过高
        expr: (1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)) * 100 > 85
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "{{ $labels.instance }} 内存使用率超过85%"
          description: "当前值: {{ $value }}%"

      - alert: 磁盘空间不足
        expr: (1 - (node_filesystem_avail_bytes{fstype!="tmpfs",fstype!="devtmpfs"} / node_filesystem_size_bytes)) * 100 > 85
        for: 10m
        labels:
          severity: critical
        annotations:
          summary: "{{ $labels.instance }} {{ $labels.mountpoint }} 磁盘使用率超过85%"
          description: "当前值: {{ $value }}%"

prometheus.yml 中启用告警规则:

rule_files:
  - "alerts.yml"
sudo systemctl restart prometheus

9.2 安装配置Alertmanager(可选,生产推荐)

Alertmanager负责接收Prometheus发出的告警,进行去重、分组、路由。小型部署可以直接用Grafana内置告警,中大型部署建议单独部署Alertmanager,支持邮件、钉钉、企业微信、Slack等渠道。

安装步骤和Prometheus类似,从 官网下载 解压后配置systemd服务即可。配置文件 alertmanager.yml 中配置告警接收渠道,然后在 prometheus.yml 中配置 alerting 段指向Alertmanager地址。

十、生产环境最佳实践

  • 数据保留期限:Prometheus默认保留15天数据,生产环境建议调整到30-90天。启动参数加 --storage.tsdb.retention.time=90d
  • 外接长期存储:Prometheus本地TSDB不适合长期存储,生产环境建议对接Thanos或VictoriaMetrics,实现长期存储和全局查询,也方便多Prometheus实例集中管理
  • 高可用:Prometheus本身无集群模式,生产环境建议部署两套Prometheus(双写),Grafana查询时配置多数据源或用录制规则聚合,避免单点故障
  • 安全:Prometheus和Grafana默认无认证,生产环境务必配置Grafana登录认证(LDAP/OAuth),Prometheus前端加反向代理(Nginx)并配置Basic Auth或JWT认证
  • 标签基数控制:标签值过多的指标会导致Prometheus内存暴涨,设计告警规则时注意控制基数,避免出现类似user_id这样的高基数标签
  • 录制规则(Recording Rules):对于查询耗时的PromQL表达式,用录制规则预先计算并存储结果,大幅提升Grafana仪表盘的加载速度

总结

Prometheus + Grafana 这套组合,从安装到跑起来,熟练的话半小时就能搞定。它能覆盖主机监控、服务监控、告警三大核心需求,是中小型团队性价比最高的监控方案。

当然,监控只是运维体系的一部分。服务器性能监控只是"看得见",真正要让系统稳定,还需要日志分析、链路追踪、自动告警等一系列工具配合。后续会持续更新相关实战内容。


相关阅读:


原创内容,转载请注明出处。如有问题欢迎留言讨论。

版权声明

本文仅代表个人观点。
本文系AI辅助作者原创,未经许可,转载请保留原文链接。

发表评论
881文章数 0评论数
作者其它文章