Prometheus: ServiceMonitors and the Prometheus Operator
A ServiceMonitor is a Kubernetes object that tells Prometheus which service to scrape. The Prometheus Operator is the program that reads it.
A ServiceMonitor for ShopSentry
The selector label picks the service. The endpoint names the port and the metrics path.
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata: {name: shopsentry}
spec:
selector: {matchLabels: {app: shopsentry}}
endpoints: [{port: web, path: /metrics, interval: 15s}]Watch the Operator work
The Operator logs show it rebuilding the Prometheus config when a ServiceMonitor changes.
kubectl logs -n monitoring deploy/prometheus-operatorSee what the Operator picked up
This lists every ServiceMonitor the Operator can see in the namespace.
kubectl get servicemonitors -n monitoringExample
which kubectl; echo "exit $?"Key points
- ServiceMonitor: a small Kubernetes file naming a service, a port, and a scrape path.
- You create one per service, and Prometheus picks it up without a config edit.
- Operator: a program that watches Kubernetes objects and turns them into real config.
- The Operator reads ServiceMonitors and rebuilds the Prometheus scrape config for you.
- Without the Operator, every new service means hand-editing prometheus.yml again.
- A ServiceMonitor selects its service with a label, so the label must match exactly.
- The Operator also manages PrometheusRule objects, which carry alerting rules as files.
- The chart from the last lesson installs the Operator, so all of this comes together.
In this example, the lab machine has no kubectl and no cluster, so the command that would list the ServiceMonitors was stated, not run. The idea still stands. A ServiceMonitor replaces the hand-written target list, and the Operator does the wiring.
Note
Like the last lesson, this one was not run against a live cluster.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
How does a ServiceMonitor tell Prometheus what to scrape?