用 Prometheus 和 Grafana 监控
你将构建什么
一个监控技术栈:带 Prometheus 指标的 Node.js 应用、抓取指标的 Prometheus 服务器,以及可视化指标的 Grafana 仪表盘。
学习目标
- 为应用埋点 Prometheus 指标
- 配置 Prometheus 抓取指标
- 设置 Grafana 数据源
- 构建监控仪表盘
前置要求
- Docker 基础
- 理解指标和时间序列
- HTTP 端点
步骤
- 1
为应用埋点指标
在 Node.js 应用中添加 prom-client 库,暴露 /metrics 端点。追踪请求计数和响应时间。
代码// app.js const express = require('express'); const promClient = require('prom-client'); const app = express(); // Collect default metrics (CPU, memory, etc.) promClient.collectDefaultMetrics(); // Custom counter const requestCount = new promClient.Counter({ name: 'http_requests_total', help: 'Total HTTP requests', labelNames: ['method', 'route'] }); // Custom histogram const responseTime = new promClient.Histogram({ name: 'http_response_time_seconds', help: 'HTTP response time in seconds', buckets: [0.1, 0.5, 1, 2, 5] }); app.use((req, res, next) => { const start = Date.now(); res.on('finish', () => { requestCount.inc({ method: req.method, route: req.route?.path || 'unknown' }); responseTime.observe((Date.now() - start) / 1000); }); next(); }); app.get('/metrics', (req, res) => res.set('Content-Type', promClient.register.contentType).end(promClient.register.metrics())); app.get('/', (req, res) => res.json({ hello: 'world' })); app.listen(3000);预期结果
应用暴露 /metrics,包含请求计数、响应时间和默认 Node.js 指标。
- 2
配置 Prometheus
创建 prometheus.yml 配置,每 15 秒抓取应用的 /metrics 端点。
代码# prometheus.yml global: scrape_interval: 15s scrape_configs: - job_name: 'node-app' static_configs: - targets: ['app:3000'] - job_name: 'prometheus' static_configs: - targets: ['localhost:9090']预期结果
Prometheus 配置为每 15 秒抓取应用和自身。
- 3
用 Docker Compose 搭建监控栈
创建 docker-compose.yml,包含应用、Prometheus 和 Grafana 服务。验收:三个服务启动且 Prometheus 能到达应用。
提示
services: app (build .), prometheus (image: prom/prometheus, volumes: ./prometheus.yml), grafana (image: grafana/grafana, ports: 3000:3000)
- 4
配置 Grafana 数据源
在 Grafana 中添加 Prometheus 作为数据源。可通过 UI 或配置文件完成。验收:Grafana 数据源测试显示 Prometheus 已连接。
提示
Create provisioning/datasources/prometheus.yml with: apiVersion: 1, datasources: [{ name: Prometheus, type: prometheus, url: http://prometheus:9090 }]
- 5
构建仪表盘
创建 Grafana 仪表盘,包含面板:请求速率(rate(http_requests_total[5m]))、P95 响应时间(histogram_quantile(0.95, rate(...)))和 CPU 使用率。验收:向应用发送请求时仪表盘显示实时数据。
代码# Key PromQL queries for the dashboard: # Request rate (requests per second) rate(http_requests_total[5m]) # P95 response time histogram_quantile(0.95, rate(http_response_time_seconds_bucket[5m])) # CPU usage percentage rate(process_cpu_seconds_total[1m]) * 100 # Memory usage process_resident_memory_bytes / 1024 / 1024预期结果
仪表盘每几秒更新显示实时指标,随流量到达应用而变化。
自己动手试试
# prometheus.yml
global:
scrape_interval: 15s
scrape_configs:
- job_name: 'app'
# TODO: add targetsscrape_configs:
- job_name: 'node-app'
static_configs:
- targets: ['app:3000']你学到了什么
你构建了完整监控技术栈 —— 为应用埋点、用 Prometheus 收集指标、用 Grafana 可视化。监控是运维生产系统的基础:你看不见的问题就无法修复。
相关资源
相关术语
- Prometheus
指标收集
- Grafana
仪表盘可视化
相关术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
- Prometheus
指标收集
- Grafana
仪表盘可视化
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。