在 Kubernetes 集群中为 Spring Boot 微服务接入 Prometheus 监控,核心链路并不复杂,但真正落地时往往卡在几个细节上:Operator 的选择器规则、Service 端口与协议匹配、Actuator 端点暴露,以及如何把监控资源优雅地收编进 Kustomize 发布流水线。

这次结合 hoteler-api(Spring Boot 4 + Micrometer)在 hoteler-dev-namespace 的部署实践,把完整配置与踩坑经验整理下来。

一、 整体思路与关键配置

集群中已通过 kube-prometheus-stack 部署了 Prometheus Operator 与 Grafana,因此最自然的接入方式是声明 ServiceMonitor,让 Operator 自动生成抓取配置,再通过 kustomization.yaml 将其纳入环境编排,同时把 application.yml 变更和镜像版本一并管理。

1. 声明 ServiceMonitor(servicemonitor.yaml)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: hoteler-api
labels:
release: prometheus
spec:
selector:
matchLabels:
app: hoteler-api
namespaceSelector:
matchNames:
- hoteler-dev-namespace
endpoints:
- port: http
path: /actuator/prometheus
interval: 15s
scheme: http

2. 纳入 Kustomize 环境清单(kustomization.yaml)

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
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

namespace: hoteler-dev-namespace

resources:
- ../../base
- certificate.yaml
- ingress.yaml
- middleware.yaml
- namespace.yaml
- servicemonitor.yaml

patches:
- path: disable-hpa.yaml

configMapGenerator:
- name: hoteler-api-config
behavior: replace
files:
- application.yml

images:
- name: ghcr.io/damingerdai/hoteler
newName: 192.168.31.220:5000/damingerdai/hoteler-api # ghcr.io/damingerdai/hoteler:v0.0.7
newTag: 6e6ea27
- name: ghcr.io/damingerdai/hoteler-web
newName: 192.168.31.220:5000/damingerdai/hoteler-web # ghcr.io/damingerdai/hoteler-web:v0.0.7
newTag: e156934

二、 实战中的四个关键细节

  • 匹配 Prometheus 实例的 serviceMonitorSelector
    kube-prometheus-stack 默认要求 ServiceMonitor 带有 release: prometheus 标签(可通过核对 Prometheus CR 的 spec.serviceMonitorSelector 确认)。漏掉这个标签,Operator 不会将其纳入抓取目标。
  • 端口名与非 TLS 协议(8443 + scheme: http)
    ServiceMonitor 中的 endpoints[].port 对应的是 Service 定义的端口名称(如 http),而不是端口号。由于 hoteler-api 的 8443 端口实际走的是 HTTP 明文而非 TLS,显式写明 scheme: http 可以避免协议误判。
  • Spring Boot Actuator 路径与配置联动
    项目引入了 spring-boot-starter-actuator 和 micrometer-registry-prometheus 后,必须确保 application.yml 中已暴露 prometheus 端点,且路径为 /actuator/prometheus。将 application.yml 放进 configMapGenerator(behavior: replace)后,配置更新可以随部署同步生效。
  • Grafana 面板选型与变量对齐
    早期的 JVM 面板模板对新版本 Spring Boot 的适配度有限,针对 Spring Boot 4 可以优先选用更贴合新指标与 Operator 标签体系的看板(如 22108 侧重 JVM/监控体系,25697 侧重 HTTP 请求延迟与错误率),导入后根据实际标签(如 job、namespace、pod)核对变量与查询语句即可出图。

三、 部署与验证清单

  1. 校验渲染结果:在提交或应用前,先用 kubectl kustomize 检查生成的资源是否包含 ServiceMonitor、更新后的 ConfigMap 以及替换后的镜像标签。
  2. 确认 Target 状态:应用生效后,在 Prometheus 的 Status -> Targets 中确认 hoteler-api 对应抓取任务状态为 UP。
  3. 验证 Grafana 出图:切换至对应的 JVM / HTTP 监控面板,确认指标曲线正常刷新且无 No data 或查询报错。

这次改动把**应用配置(Actuator 暴露)、采集规则(ServiceMonitor)、发布编排(kustomization.yaml)**串成了一个闭环,后续再接新服务或调整抓取频率时,直接复用这套结构会顺畅很多。