Service Discovery & Relabeling
Finding targets automatically and rewriting labels
Listing every target by hand in static_configs works for a lab. In
production, instances come and go every minute: autoscaling, deploys,
pods rescheduled. Service discovery (SD) asks some source of truth
what exists right now, and relabeling turns what it returns into the
target list and labels you want.
Discovery mechanisms
| Mechanism | Source of truth | Typical use |
|---|---|---|
static_configs | The config file | Labs, a few fixed hosts |
file_sd_configs | JSON/YAML files, re-read on change | Anything that can write a file: Ansible, Terraform, a cron script |
dns_sd_configs | DNS A/AAAA/SRV records | Simple fleets behind DNS |
docker_sd_configs | The Docker socket | Single-host Docker |
kubernetes_sd_configs | The Kubernetes API | Pods, services, endpoints, nodes |
consul_sd_configs | Consul catalog | Service-mesh shops |
ec2_sd_configs, gce_sd_configs, azure_sd_configs | Cloud APIs | VMs in the cloud |
http_sd_configs | Any HTTP endpoint returning target JSON | Your own inventory system |
All of them produce the same thing: a list of targets, each with an
__address__ and a set of __meta_* labels describing it (the pod's
labels, the EC2 instance's tags, and so on).
file_sd in this repo
The demo-app job uses file discovery:
- job_name: demo-app
scrape_interval: 5s
file_sd_configs:
- files: ["/etc/prometheus/targets/demo-app.json"]
refresh_interval: 30s[
{
"targets": ["demo-app:8080"],
"labels": { "env": "local", "team": "checkout" }
}
]Prometheus watches the file and applies changes without a reload.
Add a second target to the list, for example "loadgen:8080" (which has
no metrics endpoint), save, and within seconds it appears on /targets
as down. That's the whole integration surface: anything that can write
JSON can feed Prometheus.
Relabeling: the pipeline
Relabeling happens at two points, with the same syntax:
relabel_configsruns once per target, on its labels. It decides whether to scrape a target, where (__address__,__metrics_path__,__param_*), and which target labels to keep.metric_relabel_configsruns on every scraped sample. Use it to drop expensive series or fix bad label names from an exporter you don't control.
After relabel_configs, every label starting with __ is dropped.
That's why you can freely use __meta_* labels as inputs.
Relabel rule anatomy
| Action | Effect |
|---|---|
replace | Write replacement into target_label if regex matches |
keep | Drop the target/sample unless regex matches |
drop | Drop the target/sample if regex matches |
labelmap | Copy every label whose name matches regex to a new name |
labeldrop / labelkeep | Remove labels by name |
hashmod | Hash source_labels into a number, for sharding scrapes |
lowercase / uppercase | Change case |
The rules in this repo, explained
Strip the port into a host label:
relabel_configs:
- source_labels: [__address__] # "demo-app:8080"
regex: "([^:]+):\\d+"
target_label: host
replacement: "$1" # host="demo-app"Drop series nobody uses, after the scrape:
metric_relabel_configs:
- source_labels: [__name__]
regex: "python_gc_.*"
action: dropThe blackbox multi-target pattern. The target list contains the URLs to probe, but Prometheus must actually scrape the exporter:
- job_name: blackbox-http
metrics_path: /probe
params:
module: [http_2xx]
static_configs:
- targets: [http://demo-app:8080/healthz, ...]
relabel_configs:
- source_labels: [__address__] # http://demo-app:8080/healthz
target_label: __param_target # becomes ?target=http://demo-app:8080/healthz
- source_labels: [__param_target]
target_label: instance # series are labelled with what was probed
- target_label: __address__
replacement: blackbox-exporter:9115 # but the scrape goes to the exporterOpen Status → Service discovery in the Prometheus UI and click
blackbox-http. You'll see each target's labels before and after
relabeling, side by side. That page is the debugger for every relabel
rule you'll ever write.
Kubernetes, briefly
In Kubernetes the same tools do the heavy lifting. A common pattern scrapes only pods that opt in through an annotation:
- job_name: kubernetes-pods
kubernetes_sd_configs:
- role: pod
relabel_configs:
# keep only pods annotated prometheus.io/scrape: "true"
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
action: keep
regex: "true"
# copy namespace and pod name into normal labels
- source_labels: [__meta_kubernetes_namespace]
target_label: namespace
- source_labels: [__meta_kubernetes_pod_name]
target_label: pod
# copy every pod label (app, team, ...) onto the series
- action: labelmap
regex: __meta_kubernetes_pod_label_(.+)In practice most Kubernetes clusters use the Prometheus Operator,
where you declare ServiceMonitor and PodMonitor resources and the
operator generates this config for you. Underneath, it's still SD plus
relabeling.
labelmap over every Kubernetes pod label is convenient and
dangerous. If anyone adds a label like pod-template-hash or a
deploy timestamp to their pods, every series from those pods gains a
label whose value changes on every deploy. That's high churn: a whole
new set of series per rollout. Allow-list the labels you copy.
Lab
- Add
"pushgateway:9091"as a second target intargets/demo-app.json. Without reloading, find it on/targets. What's itsteamlabel? - Remove it again.
- Add a
metric_relabel_configsrule to thenodejob that dropsnode_scrape_collector_.*. Validate withpromtool check config, reload, and comparescrape_samples_post_metric_relabeling{job="node"}before and after. - In Status → Service discovery, find which
__meta_*labels file SD provides. (Hint:__meta_filepath.) Use one to add asource_filelabel to the demo-app job.