Ravindra BagaleCourses & study guides मराठी

Chapter 87: Prometheus and Grafana Monitoring

DevOps

87.5 ServiceMonitor and PodMonitor (Prometheus Operator)

Story. On kind, Sara used to edit prometheus.yml by hand. After they installed kube-prometheus-stack (Helm, chapter 85 style), she created a ServiceMonitor CR. The Prometheus Operator watched it and updated scrape config for her. No more SSH into the Prometheus pod to add targets.

You create ServiceMonitor. Operator updates Prometheus scrape config. Targets appear UP.
You create ServiceMonitor. Operator updates Prometheus scrape config. Targets appear UP.

Why

On Kubernetes, pods come and go. Static IP lists rot. ServiceMonitor follows Services and Endpoints.

What

  • Prometheus Operator — Controllers that manage Prometheus, Alertmanager and scrape CRs.
  • ServiceMonitor — CR that says "scrape this Service's pods on this port and path".
  • PodMonitor — Same idea but selects Pods directly (useful for DaemonSets without a Service).
  • label selector — How ServiceMonitor finds Services (matchLabels).
  • release label — Many Helm charts require ServiceMonitors to carry the same label the Prometheus CR selects (often release: kube-prometheus-stack or similar — check your values).

How

  1. Install kube-prometheus-stack with Helm (lab later).
  2. Expose your app with a Service that has a named metrics port.
  3. Write a ServiceMonitor in the same namespace (or allow cross-namespace in values).
  4. Match the labels your Prometheus instance selects.
  5. Check Targets in Prometheus UI.

Example 1: ServiceMonitor YAML

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: shop-api
  namespace: shop
  labels:
    release: kube-prometheus-stack
spec:
  selector:
    matchLabels:
      app: shop-api
  endpoints:
    - port: http-metrics
      path: /metrics
      interval: 30s

What it shows: Operator will scrape pods behind Services labeled app=shop-api, port name http-metrics, path /metrics.

Example 2: Confirm the Service port name

kubectl get svc shop-api -n shop -o yaml | grep -A6 "ports:"

Output

  ports:
  - name: http-metrics
    port: 8080
    targetPort: 8080

What it shows: The port name must match endpoints.port in the ServiceMonitor. Wrong name means silent empty targets.

Ravindra Bagale's Tip

If Targets stay empty, first check ServiceMonitor labels against the Prometheus CR serviceMonitorSelector — that mismatch is the classic bug.

Quick quiz

Q1. What creates scrape config for you on Kubernetes?

The Prometheus Operator, driven by ServiceMonitor or PodMonitor CRs.

Q2. ServiceMonitor selects what?

Services (then their Endpoint pods) by label.

Q3. Why does port name matter?

ServiceMonitor endpoints.port must match the Service port name.

Did you understand? Let us try it once more.