Prometheus + Grafana 监控环境搭建完全指南
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 sudo useradd --no-create-home --shell /usr/sbin/nologin prometheussudo mkdir -p /etc/prometheus /var/lib/prometheuscd /tmpwget 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-amd64sudo cp prometheus promtool /usr/local/bin/sudo cp -r consoles console_libraries /etc/prometheus/sudo tee /etc/prometheus/prometheus.yml > /dev/null << 'EOF' global: scrape_interval: 15s evaluation_interval: 15s alerting: alertmanagers: - static_configs: - targets: [] rule_files: scrape_configs: - job_name: "prometheus" static_configs: - targets: ["localhost:9090" ] EOF sudo chown -R prometheus:prometheus /etc/prometheus /var/lib/prometheussudo 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 sudo systemctl daemon-reloadsudo systemctl enable prometheussudo systemctl start prometheussudo 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/datadocker 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 sudo useradd --no-create-home --shell /usr/sbin/nologin node_exportercd /tmpwget 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-amd64sudo cp node_exporter /usr/local/bin/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 sudo systemctl daemon-reloadsudo systemctl enable node_exportersudo 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 sudo apt-get install -y software-properties-commonsudo add-apt-repository "deb https://packages.grafana.net/oss/deb stable main" wget -q -O - https://packages.grafana.net/gpg.key | sudo apt-key add - sudo apt-get updatesudo apt-get install -y grafanasudo systemctl daemon-reloadsudo systemctl enable grafana-serversudo 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
访问 http://服务器IP:3000,默认用户名和密码均为 admin
首次登录会提示修改密码
进入 Configuration → Data Sources → Add data source
选择 Prometheus
在 URL 字段填写 http://localhost:9090(如果 Grafana 与 Prometheus 在同一台服务器)
点击 Save & Test ,看到 “Data source is working” 即为成功
导入仪表板 Grafana 拥有丰富的社区仪表板模板,可直接导入:
点击左侧 + → Import
在 “Import via grafana.com” 输入仪表板 ID:
Node Exporter Full(ID: 1860) :最全面的 Linux 系统监控仪表板
Node Exporter Server Metrics(ID: 11074) :简洁版本
选择数据源为 Prometheus
点击 Import
仪表板名称 ID 监控指标
Node Exporter Full 1860 CPU、内存、磁盘、网络、负载、进程
Prometheus 2.0 Stats 3662 Prometheus 自身性能指标
1 Node Overview for Prometheus 11074 简洁版单节点概览
Blackbox Exporter 7587 HTTP/HTTPS/ICMP 探测
Docker Monitoring 179 Docker 容器监控
五、添加更多 Exporters 常见 Exporter 列表 除了 Node Exporter,Prometheus 生态提供了大量的 Exporter:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 docker run -d --name blackbox_exporter --restart unless-stopped -p 9115:9115 prom/blackbox-exporter:latest docker run -d --name mysql_exporter --restart unless-stopped -p 9104:9104 \ -e DATA_SOURCE_NAME="user:password@(localhost:3306)/" \ prom/mysqld-exporter:latest 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 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: - 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 sudo apt-get install -y apache2-utilshtpasswd -c /etc/prometheus/web.yml admin sudo ufw allow 22/tcp sudo ufw allow 80/tcp sudo ufw allow 443/tcp sudo ufw allow 3000/tcp sudo ufw deny 9090/tcp sudo ufw deny 9100/tcp
九、验证与测试 安装完成后,按以下步骤验证监控栈是否正常工作:
1 2 3 4 5 6 7 8 9 10 11 12 13 curl http://localhost:9090/-/ready curl http://localhost:9100/metrics | head -20 curl 'http://localhost:9090/api/v1/query?query=up' curl http://localhost:3000/api/health
在 Prometheus Web UI 的 Status → Targets 页面,可以看到所有配置的抓取目标及其健康状态。所有目标显示为 UP 状态,说明配置正确。
十、总结 本文详细介绍了从零搭建 Prometheus + Grafana 监控栈的完整流程,包括:
Prometheus Server 的两种安装方式(二进制和 Docker)
Node Exporter 部署与系统指标采集
Grafana 安装配置与仪表板导入
多种 Exporter 的扩展部署
告警规则 的编写与配置
PromQL 常用查询语句
安全加固 最佳实践
这套监控栈轻量、易扩展、社区活跃,足以应对从小型服务器到大型集群的各种监控需求。后续还可以接入 Alertmanager 实现多通道告警通知(邮件、钉钉、Slack、企业微信等),以及部署 Prometheus 联邦集群来监控跨区域的多数据中心。
本文由AI辅助生成,内容仅供参考