Learn Labs
Instrumentation & Exporters

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

MechanismSource of truthTypical use
static_configsThe config fileLabs, a few fixed hosts
file_sd_configsJSON/YAML files, re-read on changeAnything that can write a file: Ansible, Terraform, a cron script
dns_sd_configsDNS A/AAAA/SRV recordsSimple fleets behind DNS
docker_sd_configsThe Docker socketSingle-host Docker
kubernetes_sd_configsThe Kubernetes APIPods, services, endpoints, nodes
consul_sd_configsConsul catalogService-mesh shops
ec2_sd_configs, gce_sd_configs, azure_sd_configsCloud APIsVMs in the cloud
http_sd_configsAny HTTP endpoint returning target JSONYour 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:

discovery__address__, __meta_*relabel_configsper targetscrapeGET /metricsmetric_relabelper sampleTSDBtarget droppedaction: keep/dropseries droppedpython_gc_*
  • relabel_configs runs 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_configs runs 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

- source_labels: [a, b]values joined with separator (default ";")separator: ";"regex: "(.+);(.+)"fully anchored RE2 regex, default "(.*)"target_label: clabel to writereplacement: "$1-$2"with capture groups, default "$1"action: replacedefault
ActionEffect
replaceWrite replacement into target_label if regex matches
keepDrop the target/sample unless regex matches
dropDrop the target/sample if regex matches
labelmapCopy every label whose name matches regex to a new name
labeldrop / labelkeepRemove labels by name
hashmodHash source_labels into a number, for sharding scrapes
lowercase / uppercaseChange 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: drop

The 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 exporter

Open 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.

Lab

  1. Add "pushgateway:9091" as a second target in targets/demo-app.json. Without reloading, find it on /targets. What's its team label?
  2. Remove it again.
  3. Add a metric_relabel_configs rule to the node job that drops node_scrape_collector_.*. Validate with promtool check config, reload, and compare scrape_samples_post_metric_relabeling{job="node"} before and after.
  4. In Status → Service discovery, find which __meta_* labels file SD provides. (Hint: __meta_filepath.) Use one to add a source_file label to the demo-app job.

On this page