Service Discovery & the Prometheus Operator
Static target lists work for a few fixed servers. In Kubernetes or an autoscaling group, targets come and go every minute, so Prometheus asks a service discovery (SD) mechanism for the current list and refreshes it continuously.
SD mechanisms
| Mechanism | Discovers | Typical use |
|---|---|---|
kubernetes_sd_configs |
nodes, pods, services, endpoints, endpointslices, ingresses | anything in a cluster |
file_sd_configs |
targets listed in JSON/YAML files, reloaded on change | a script or config-management tool writes the files |
http_sd_configs |
a URL returning the same JSON | an internal inventory service |
ec2_sd_configs, azure_sd_configs, gce_sd_configs |
cloud VMs, with tags as __meta_* labels |
VMs outside Kubernetes |
consul_sd_configs, dns_sd_configs |
Consul services, DNS SRV/A records | classic service registries |
All of them produce the same thing: a list of targets with an __address__ and many __meta_* labels. Relabeling then turns that into what you want (Scrape Configuration & Relabeling).
A file_sd file looks like this:
[
{ "targets": ["10.0.1.5:8080", "10.0.1.6:8080"], "labels": { "env": "staging" } },
{ "targets": ["10.0.3.7:9100"], "labels": { "env": "staging", "job": "node" } }
]Kubernetes SD by hand
With the pod role, Prometheus gets one target per container port of every pod, labelled with __meta_kubernetes_namespace, __meta_kubernetes_pod_name, __meta_kubernetes_pod_label_<name>, __meta_kubernetes_pod_annotation_<name>, __meta_kubernetes_pod_container_port_number and more. The classic convention is to scrape pods that carry a prometheus.io/scrape: "true" annotation:
scrape_configs:
- job_name: kubernetes-pods
kubernetes_sd_configs:
- role: pod
relabel_configs:
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
regex: "true"
action: keep
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
regex: (.+)
target_label: __metrics_path__
- source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
regex: '([^:]+)(?::\d+)?;(\d+)'
replacement: '$1:$2'
target_label: __address__
- action: labelmap
regex: __meta_kubernetes_pod_label_(.+)
- source_labels: [__meta_kubernetes_namespace]
target_label: namespace
- source_labels: [__meta_kubernetes_pod_name]
target_label: podThere is no cluster in the sandbox, but the relabeling can be tested: the session below feeds two "pods" as static targets carrying the same __meta_* labels Kubernetes SD would produce, and runs the rules with promtool check service-discovery:
cat > prometheus.yml <<'YML'
scrape_configs:
- job_name: kubernetes-pods
static_configs: # stand-in for kubernetes_sd_configs: same labels SD would attach
- targets: ["10.42.0.17:8080"]
labels:
__meta_kubernetes_namespace: links
__meta_kubernetes_pod_name: linkly-7d9f-x2k4p
__meta_kubernetes_pod_label_app: linkly
__meta_kubernetes_pod_annotation_prometheus_io_scrape: "true"
__meta_kubernetes_pod_annotation_prometheus_io_port: "9102"
- targets: ["10.42.0.23:6379"]
labels:
__meta_kubernetes_namespace: links
__meta_kubernetes_pod_name: redis-0
__meta_kubernetes_pod_label_app: redis
relabel_configs:
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
regex: "true"
action: keep
- source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
regex: '([^:]+)(?::\d+)?;(\d+)'
replacement: '$1:$2'
target_label: __address__
- action: labelmap
regex: __meta_kubernetes_pod_label_(.+)
- source_labels: [__meta_kubernetes_namespace]
target_label: namespace
- source_labels: [__meta_kubernetes_pod_name]
target_label: pod
YML
promtool check service-discovery prometheus.yml kubernetes-pods |
jq -c '.[] | .labels | with_entries(select(.key | startswith("__") | not))'{"app":"linkly","instance":"10.42.0.17:9102","job":"kubernetes-pods","namespace":"links","pod":"linkly-7d9f-x2k4p"}
{}
Redis had no annotation, so it was dropped (empty labels); linkly is scraped on the annotated port 9102, with app, namespace and pod labels.
Annotations are simple but limited: one port and path per pod, no TLS settings, and every team edits the central prometheus.yml. That's why most clusters use the Operator instead.
The Prometheus Operator
The Prometheus Operator (installed by kube-prometheus-stack) manages Prometheus and Alertmanager as Kubernetes resources and generates prometheus.yml from custom resources that teams create next to their apps:
| CRD | Purpose |
|---|---|
Prometheus, Alertmanager |
the servers themselves: replicas, retention, storage, which monitors to select |
ServiceMonitor |
scrape the endpoints behind a Service, selected by labels |
PodMonitor |
scrape pods directly (no Service) |
PrometheusRule |
recording and alerting rules |
AlertmanagerConfig |
a namespaced piece of the routing tree |
ScrapeConfig |
raw scrape configs (file SD, static targets, cloud SD) as a resource |
linkly's chart ships a ServiceMonitor:
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: linkly
namespace: links
labels:
release: monitoring # must match the Prometheus resource's serviceMonitorSelector
spec:
selector:
matchLabels:
app.kubernetes.io/name: linkly
endpoints:
- port: http # the *name* of the Service port
path: /metrics
interval: 15sand its rules as a PrometheusRule (the spec is exactly a rule file's groups:):
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: linkly
namespace: links
labels:
release: monitoring
spec:
groups:
- name: linkly
rules:
- alert: LinklyDown
expr: up{job="linkly"} == 0
for: 2m
labels: {severity: page}The most common "my metrics don't show up" cause is a selector mismatch: kube-prometheus-stack's Prometheus only picks up ServiceMonitors with the label release: <helm release name> (unless you set serviceMonitorSelectorNilUsesHelmValues: false). Check Status → Targets and the operator's logs. The ServiceMonitor schema can be validated offline with kubeconform (its CRD schemas are in the Helm & Kustomize course's sandbox).
# sample session against a cluster
$ kubectl -n links get servicemonitors,prometheusrules
NAME AGE
servicemonitor.monitoring.coreos.com/linkly 3d
NAME AGE
prometheusrule.monitoring.coreos.com/linkly 3d
$ kubectl -n monitoring get prometheus -o jsonpath='{.items[0].spec.serviceMonitorSelector}'
{"matchLabels":{"release":"monitoring"}}Test yourself
What does relabeling do with the __meta_* labels that service discovery provides?
- Stores them on every series
- Uses them to filter and build target labels; anything starting with
__is dropped afterwards - Sends them to Alertmanager
- Nothing; they are informational only
A team's ServiceMonitor exists but its targets never appear. What should you check first?
- The Grafana dashboard
- Whether its labels match the Prometheus resource's serviceMonitorSelector (and the namespace selector)
- The scrape_timeout
- Alertmanager routing
Which CRD carries alerting and recording rules for the Prometheus Operator?
- ServiceMonitor
- PrometheusRule
- AlertmanagerConfig
- PodMonitor