运维监控及可视化工具Prometheus和grafana

张开发
2026/4/11 15:41:02 15 分钟阅读

分享文章

运维监控及可视化工具Prometheus和grafana
运维监控及可视化工具Prometheus 是一款强大的开源监控和告警工具而 Grafana 是一个流行的数据可视化工具两者结合可以构建完整的监控和可视化解决方案。以下是 Prometheus 的使用、进阶内容详解以及 Grafana 的使用指南。一、Prometheus 使用详解1. 核心概念指标Metric时间序列数据由指标名称和标签Key-Value对唯一标识。示例http_requests_total{methodGET, status200}。样本Sample时间序列数据的具体值包含时间戳和数值。示例http_requests_total{methodGET, status200} 1622548800 100。2. 安装与配置安装 Prometheuswget https://github.com/prometheus/prometheus/releases/download/v2.30.3/prometheus-2.30.3.linux-amd64.tar.gz tar -xzf prometheus-2.30.3.linux-amd64.tar.gz cd prometheus-2.30.3.linux-amd64 ./prometheus --config.fileprometheus.yml配置文件prometheus.ymlglobal: scrape_interval: 15s # 采集间隔 scrape_configs: - job_name: prometheus static_configs: - targets: [localhost:9090]3. 使用 Node Exporter 监控主机安装 Node Exporterwget https://github.com/prometheus/node_exporter/releases/download/v1.2.2/node_exporter-1.2.2.linux-amd64.tar.gz tar -xzf node_exporter-1.2.2.linux-amd64.tar.gz cd node_exporter-1.2.2.linux-amd64 ./node_exporter配置 Prometheus 采集yamlscrape_configs: - job_name: node static_configs: - targets: [localhost:9100]4. 使用 PromQL 查询数据基本查询promql# 查询CPU使用率 100 - (avg by (instance) (irate(node_cpu_seconds_total{modeidle}[1m])) * 100) # 查询内存使用率 (node_memory_MemTotal_bytes - node_memory_MemFree_bytes) / node_memory_MemTotal_bytes * 100聚合查询promql# 按实例统计HTTP请求总数 sum(http_requests_total) by (instance) # 计算5分钟内请求速率 rate(http_requests_total[5m])5. 配置告警规则告警规则文件alerts.ymlyamlgroups: - name: example rules: - alert: HighCPUUsage expr: 100 - (avg by (instance) (irate(node_cpu_seconds_total{modeidle}[1m])) * 100) 80 for: 5m labels: severity: critical annotations: summary: High CPU usage on {{ $labels.instance }} description: CPU usage is above 80% for 5 minutes.配置 Prometheus 加载告警规则yamlrule_files: - alerts.yml6. 配置 Alertmanager安装 Alertmanagerwget https://github.com/prometheus/alertmanager/releases/download/v0.23.0/alertmanager-0.23.0.linux-amd64.tar.gz tar -xzf alertmanager-0.23.0.linux-amd64.tar.gz cd alertmanager-0.23.0.linux-amd64 ./alertmanager配置文件alertmanager.ymlroute: receiver: email receivers: - name: email email_configs: - to: adminexample.com from: alertmanagerexample.com smarthost: smtp.example.com:587 auth_username: user auth_password: password二、Prometheus 进阶内容1. 高可用部署多实例部署部署多个 Prometheus 实例采集相同目标。使用负载均衡器如 HAProxy分发查询请求。远程存储使用 Thanos 或 Cortex 实现长期存储和全局查询。2. 长期存储Thanos提供全局查询、数据压缩和长期存储功能。示例架构Sidecar与 Prometheus 实例集成上传数据到对象存储。Query提供统一的查询接口。Store Gateway从对象存储读取数据。Cortex提供多租户支持和水平扩展能力。3. 动态服务发现Kubernetes 服务发现yamlscrape_configs: - job_name: kubernetes kubernetes_sd_configs: - role: pod relabel_configs: - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape] action: keep regex: trueConsul 服务发现yamlscrape_configs: - job_name: consul consul_sd_configs: - server: localhost:85004. 自定义 Exporter使用 Prometheus Client Library示例Pythonfrom prometheus_client import start_http_server, Gauge import random import time # 定义指标 temperature Gauge(temperature_celsius, Current temperature in Celsius) def collect_metrics(): while True: temperature.set(random.uniform(20, 30)) time.sleep(10) if __name__ __main__: start_http_server(8000) collect_metrics()5. 性能优化减少采集频率调整scrape_interval和evaluation_interval。优化 PromQL 查询避免高基数标签如用户ID。使用rate()和irate()代替count()。水平扩展使用分片Sharding将采集任务分配到多个 Prometheus 实例。三、Grafana 使用详解1. 安装与配置安装 Grafanabash复制wget https://dl.grafana.com/oss/release/grafana-8.1.5.linux-amd64.tar.gz tar -xzf grafana-8.1.5.linux-amd64.tar.gz cd grafana-8.1.5 ./bin/grafana-server访问 Grafana浏览器访问http://localhost:3000默认用户名和密码为admin/admin。2. 添加 Prometheus 数据源登录 Grafana。点击左侧菜单的Configuration→Data Sources→Add data source。选择Prometheus填写 URL如http://localhost:9090。点击Save Test。3. 创建仪表盘点击左侧菜单的Create→Dashboard。点击Add new panel。在Query选项卡中选择 Prometheus 数据源输入 PromQL 查询如rate(http_requests_total[1m])。配置图表类型如折线图、柱状图。点击Apply保存面板。4. 使用模板变量在仪表盘设置中点击Variables→Add variable。配置变量如instance查询label_values(node_cpu_seconds_total, instance)。在面板查询中使用变量如rate(node_cpu_seconds_total{instance$instance}[1m])。5. 告警与通知在面板设置中点击Alert→Create alert。配置告警规则如WHEN avg() OF query(A, 1m, now) IS ABOVE 80。配置通知渠道如 Email、Slack。四、Prometheus Grafana 最佳实践分层监控基础设施层使用 Node Exporter 监控主机。中间件层使用 MySQL Exporter、Redis Exporter 等。应用层自定义指标暴露。统一告警使用 Alertmanager 集中管理告警Grafana 作为可视化补充。长期存储使用 Thanos 或 Cortex 存储历史数据Grafana 查询展示。五、推荐学习资源官方文档Prometheus 官方文档Grafana 官方文档书籍《Prometheus: Up Running》入门与实战指南。《Monitoring with Prometheus》深入讲解 Prometheus 原理与实践。在线课程Udemy: “Prometheus and Grafana: The Complete Guide”Pluralsight: “Monitoring Systems with Prometheus”通过以上内容你可以全面掌握 Prometheus 和 Grafana 的使用方法并构建高效的监控与可视化系统。PromQL基础PromQLPrometheus Query Language是 Prometheus 的核心查询语言用于从时间序列数据库中提取和操作数据。以下是 PromQL 的详细使用指南涵盖基本查询、聚合操作、函数使用及常见场景示例。一、PromQL 基础1. 数据模型时间序列由指标名称Metric Name和标签Labels唯一标识。示例http_requests_total{methodGET, status200}。样本时间序列的具体值包含时间戳和数值。示例http_requests_total{methodGET, status200} 1622548800 100。2. 数据类型瞬时向量Instant Vector某一时刻的时间序列数据。示例http_requests_total{methodGET}。范围向量Range Vector某一时间段内的时间序列数据。示例http_requests_total{methodGET}[5m]。标量Scalar单个数值。示例count(http_requests_total)。二、基本查询1. 查询瞬时向量查询所有 HTTP 请求总数promql复制http_requests_total查询特定标签的 HTTP 请求promql复制http_requests_total{methodGET, status200}2. 查询范围向量查询过去 5 分钟的 HTTP 请求promql复制http_requests_total{methodGET}[5m]3. 使用函数计算 HTTP 请求速率promql复制rate(http_requests_total{methodGET}[1m])计算 HTTP 请求增量promql复制increase(http_requests_total{methodGET}[1h])三、聚合操作1. 按标签聚合按方法统计 HTTP 请求总数promql复制sum(http_requests_total) by (method)按方法和状态统计 HTTP 请求总数promql复制sum(http_requests_total) by (method, status)2. 全局聚合统计所有 HTTP 请求总数promql复制sum(http_requests_total)统计 HTTP 请求的平均值promql复制avg(http_requests_total)3. 分位数计算 HTTP 请求延迟的 95 分位数promql复制histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket[5m])) by (le))四、常见场景示例1. 监控 CPU 使用率计算 CPU 使用率promql复制100 - (avg by (instance) (irate(node_cpu_seconds_total{modeidle}[1m])) * 100)2. 监控内存使用率计算内存使用率promql复制(node_memory_MemTotal_bytes - node_memory_MemFree_bytes) / node_memory_MemTotal_bytes * 1003. 监控磁盘 I/O计算磁盘读写速率promql复制rate(node_disk_read_bytes_total[1m]) rate(node_disk_written_bytes_total[1m])4. 监控网络流量计算网络接收/发送速率promql复制rate(node_network_receive_bytes_total[1m]) rate(node_network_transmit_bytes_total[1m])五、高级查询1. 子查询计算过去 5 分钟内 HTTP 请求的 1 分钟速率promql复制rate(http_requests_total[1m])[5m:]2. 预测磁盘填满时间使用predict_linear预测磁盘填满时间promql复制predict_linear(node_filesystem_free_bytes{mountpoint/}[1h], 3600*24)3. 多指标计算计算请求成功率promql复制sum(rate(http_requests_total{status~2..}[1m])) / sum(rate(http_requests_total[1m])) * 100六、调试与优化1. 调试查询使用 Prometheus Web UI 的Graph或Console页面测试查询。使用explain命令查看查询执行计划需启用--enable-featurepromql-experimental。2. 优化查询避免高基数标签高基数标签如用户ID会导致查询性能下降。示例http_requests_total{user_id12345}。使用范围向量函数如rate()和irate()避免直接查询原始数据。七、推荐学习资源官方文档PromQL 官方文档书籍《Prometheus: Up Running》入门与实战指南。《Monitoring with Prometheus》深入讲解 Prometheus 原理与实践。在线课程Udemy: “Prometheus and Grafana: The Complete Guide”Pluralsight: “Monitoring Systems with Prometheus”通过以上内容你可以全面掌握 PromQL 的使用方法并应用于实际监控场景中

更多文章