必须通过prometheus operator创建servicemonitor资源,其label selector需与目标service的labels精确匹配,且servicemonitor须位于prometheus可扫描的命名空间内;同时prometheus cr需配置正确的servicemonitorselector,service的selector须匹配pod labels,namespaceselector也需显式指定service所在命名空间。

要在 Kubernetes 集群中让 Prometheus 自动发现并监控服务,必须通过 Prometheus Operator 创建 ServiceMonitor 资源,使 Operator 将其转化为实际的 scrape 配置注入到 Prometheus 实例中;这要求 ServiceMonitor 的 label selector 与目标 Service 的 labels 精确匹配,且该 ServiceMonitor 必须位于 Prometheus 实例能扫描到的命名空间内,否则指标永远不会出现在 Targets 页面。
确认 Prometheus 实例已启用 ServiceMonitor 发现
检查你部署的 Prometheus 自定义资源(Prometheus CR)是否设置了 【serviceMonitorSelector】 字段,并指向正确的标签。例如:
spec:
serviceMonitorSelector:
matchLabels:
release: prometheus
若该字段缺失或 selector 不匹配任何 ServiceMonitor,Operator 就不会为其生成抓取配置。你可以用 kubectl get prometheus -n monitoring -o yaml 查看实际值。
为待监控服务创建配套 Service
ServiceMonitor 本身不直接关联 Pod,而是通过 Service 的 Endpoints 发现后端实例。因此必须先存在一个 Service,且其 selector 能正确匹配目标 Pod 的 labels。
例如,你要监控一个 deployment 标签为 app=nginx 的应用,就需确保有如下 Service:
apiVersion: v1
kind: Service
metadata:
name: nginx-svc
namespace: default
labels:
app: nginx
spec:
selector:
app: nginx
ports:
- port: 80
targetPort: 80
注意:Service 的 labels(如 app: nginx)将用于后续 ServiceMonitor 的 matchLabels,二者必须一致。
编写并部署 ServiceMonitor
方法一:基础声明式写法
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: nginx-monitor
namespace: monitoring
labels:
release: prometheus
spec:
selector:
matchLabels:
app: nginx
namespaceSelector:
matchNames:
- default
endpoints:
- port: http
interval: 30s
关键点:【namespaceSelector.matchNames 必须显式列出 Service 所在命名空间】,默认不会跨 namespace 扫描;若 Service 在 default 命名空间,这里就必须写 - default。
方法二:复用 Service 注解自动启用(免写 selector)
给 Service 加注解 prometheus.io/scrape: "true",再创建一个宽泛匹配的 ServiceMonitor:
spec:
selector:
matchExpressions:
- key: prometheus.io/scrape
operator: Exists
namespaceSelector:
any: true
这种方式适合批量启用,但要注意 any: true 可能引入非预期服务,生产环境慎用。
验证 ServiceMonitor 是否生效
第一步:确认 ServiceMonitor 已被 Operator 接收
kubectl get servicemonitor -A | grep nginx-monitor
第二步:检查 Prometheus 实例日志中是否出现 reload 成功提示
kubectl logs -n monitoring deploy/prometheus-operator | grep -i "nginx-monitor"
第三步:进入 Prometheus UI → Status → Targets → 查找 job_name 为 serviceMonitor/monitoring/nginx-monitor/0 的分组,状态应为 UP,且显示对应 endpoints 地址。
如果 Targets 页面始终为空,大概率是 ServiceMonitor 的 namespaceSelector 或 selector 与 Service 的 labels 不匹配,或者 Prometheus CR 的 serviceMonitorSelector 没覆盖到该 ServiceMonitor 的 labels。











