第 6 章 · 监控观测:Prometheus / Grafana / 集群插件
6.1 Prometheus 2.53
适用场景
| 选用 | 说明 |
|---|---|
| 采集 指标(metrics) | CPU、QPS、延迟、业务计数器 |
| Kubernetes / 中间件监控 | 拉取 /metrics 端点 |
| 告警规则(Alertmanager 扩展) | promql 表达式触发 |
不选用:日志全文检索(用 ES);链路追踪(用 Jaeger,商店有目录)。
部署方式对比
| 方式 | 入口 | 适用 |
|---|---|---|
| 集群插件 | 管理 → 集群插件 → Prometheus + Grafana | 快速一体,NodePort 30090/30300 |
| 应用商店 | id prometheus | 独立 Namespace、自定义 scrape |
以下以 应用商店单容器 说明配置语法;插件版 Prometheus 已预置基础 scrape。
商店部署参数
| 项 | 值 |
|---|---|
| id | prometheus |
| 镜像 | prom/prometheus:v2.53.0 |
| 端口 | 9090 |
| PVC | 20 Gi → /prometheus |
核心配置语法(prometheus.yml)
通过 工作负载 YAML 挂载 ConfigMap 或确认页自定义 command:
global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_configs:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
- job_name: 'kubernetes-pods'
kubernetes_sd_configs:
- role: pod
relabel_configs:
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
action: keep
regex: true
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_port]
action: replace
target_label: __address__
regex: (.+)
replacement: ${1}
- job_name: 'mysql-exporter'
static_configs:
- targets: ['mysql-exporter:9104']
PromQL 查询语法
# CPU 使用率(示例)
100 - (avg(rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)
# HTTP QPS
sum(rate(http_requests_total[1m]))
# 延迟 P99
histogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket[5m])) by (le))
# 告警规则示例
avg_over_time(up{job="api"}[5m]) < 1
HTTP API
# 即时查询
curl 'http://prometheus:9090/api/v1/query?query=up'
# 范围查询
curl 'http://prometheus:9090/api/v1/query_range?query=up&start=...&end=...&step=15s'
# 目标状态
curl http://prometheus:9090/api/v1/targets
业务埋点(应用暴露 metrics)
Spring Boot Actuator + Micrometer
management:
endpoints:
web:
exposure:
include: health,prometheus
metrics:
tags:
application: order-service
Pod 注解(供 K8s 服务发现):
metadata:
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "8080"
prometheus.io/path: "/actuator/prometheus"