ServiceMonitor
- Docker & Kubernetes course
- Advanced
- Lesson 50/70
- 4 min
Learn scrape targets with a ServiceMonitor.
ServiceMonitor
With the Prometheus Operator, targets aren't configured by hand; a custom resource called a ServiceMonitor defines which Services are read through which port and path. The operator turns this into Prometheus configuration:
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: api
namespace: izleme
labels:
release: izleme
spec:
namespaceSelector:
matchNames: [magaza]
selector:
matchLabels:
app: api
endpoints:
- port: http
path: /metrics
interval: 30sWhy the release label?
The Prometheus object only selects ServiceMonitors carrying certain labels; in kube-prometheus-stack the default selector is release: <release-name>. If the label is missing, the ServiceMonitor is ignored and the target doesn't appear on Prometheus's Targets page:
$ kubectl get prometheus -n izleme -o jsonpath='{.items[0].spec.serviceMonitorSelector}'
{"matchLabels":{"release":"izleme"}}
kubectl get servicemonitors -APractice Write a ServiceMonitor
Write a ServiceMonitor YAML: monitoring.coreos.com/v1; name api, namespace izleme, label release: izleme; selector.matchLabels app: api; a single endpoint: port: http, path: /metrics, interval: 30s.
Starter code
# buraya yazSample solution
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: api
namespace: izleme
labels:
release: izleme
spec:
selector:
matchLabels:
app: api
endpoints:
- port: http
path: /metrics
interval: 30sExpected output
servicemonitor.monitoring.coreos.com/api created
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does port: http in a ServiceMonitor refer to?
- The NodePort
- A named port on the target Service Correct answer
- The container number
- Prometheus's port
Explanation: The Service must define ports[].name: http.
2 Write the list of endpoints to read.
spec:
selector:
matchLabels:
app: api
____:
- port: http
path: /metrics
spec:
selector:
matchLabels:
app: api
endpoints:
- port: http
path: /metrics
Explanation: endpoints contains port, path and interval.
3 Match.
| Term | Meaning |
|---|---|
ServiceMonitor |
Target definition |
namespaceSelector |
Which namespaces |
selector |
Which Services |
release etiketi |
Prometheus's selection |