Service discovery & relabeling

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

A Prometheus scrape_config names a job and, separately, how it finds the targets that job scrapes. Static lists work for small, stable setups, but anything that grows or churns — a fleet behind an inventory system, a Kubernetes cluster, an autoscaling group — needs Prometheus to ask something else for the current target list. This page covers the discovery mechanisms that feed a job (static_configs, file_sd_configs, http_sd_configs, and a brief survey of consul_sd_configs/ec2_sd_configs/ kubernetes_sd_configs), then the two relabeling stages that turn discovered targets and their raw metadata into the labels that actually reach storage: relabel_configs, which runs before a target is scraped, and metric_relabel_configs, which runs after, on the scraped samples themselves. The full scrape_config schema, including every discovery mechanism’s own options, is documented at Configuration. For the groundwork — what a scrape config is and how prometheus.yml is structured — see Getting Started.

The target pipeline at a glance

Discovery and relabeling are easiest to reason about as one pipeline with two relabeling stages, one on each side of the actual scrape:

flowchart LR SD["Service discovery
static, file, http, consul ..."] --> DL["Discovered labels
__address__, __meta_*, job"] DL --> RC{"relabel_configs"} RC -- "keep / drop" --> X["Target dropped,
never scraped"] RC -- "labels rewritten" --> TL["Target labels
instance, job, team ..."] TL --> SC["HTTP scrape of
__address__ + metrics_path"] SC --> MR{"metric_relabel_configs"} MR -- "drop" --> Y["Sample discarded"] MR -- "kept or rewritten" --> DB[("TSDB")]

The sections below walk through this with one lab configuration, a Prometheus 3.5 server in Docker that scrapes the running example (orders-api), node_exporter and the Pushgateway, and whose complete configuration is:

global:
  scrape_interval: 5s

scrape_configs:
  - job_name: file-sd
    file_sd_configs:
      - files: ["/etc/prometheus/targets/*.json"]
        refresh_interval: 5s
    relabel_configs:
      - source_labels: [team]
        regex: orders|infra
        action: keep
      - source_labels: [__meta_filepath]
        regex: ".*/(.*)\\.json"
        target_label: sd_file
        replacement: "$1"
      - source_labels: [team, tier]
        separator: "/"
        target_label: owner
    metric_relabel_configs:
      - source_labels: [__name__]
        regex: "python_gc_.*"
        action: drop

  - job_name: node-lean
    static_configs:
      - targets: ["host.docker.internal:29100"]
    metric_relabel_configs:
      - source_labels: [__name__]
        regex: "node_(cpu|memory|filesystem)_.*"
        action: keep

  - job_name: http-sd
    http_sd_configs:
      - url: http://host.docker.internal:28105/targets
        refresh_interval: 5s

  - job_name: shard-0
    file_sd_configs:
      - files: ["/etc/prometheus/targets/*.json"]
        refresh_interval: 5s
    relabel_configs:
      - source_labels: [__address__, tier]
        modulus: 2
        target_label: __tmp_hash
        action: hashmod
      - source_labels: [__tmp_hash]
        regex: "0"
        action: keep

  - job_name: shard-1
    file_sd_configs:
      - files: ["/etc/prometheus/targets/*.json"]
        refresh_interval: 5s
    relabel_configs:
      - source_labels: [__address__, tier]
        modulus: 2
        target_label: __tmp_hash
        action: hashmod
      - source_labels: [__tmp_hash]
        regex: "1"
        action: keep

Use promtool check config on it before loading it (it also warns when a file_sd glob matches nothing, as it did here when run outside the container). The next sections refer back to the jobs in this file.

Service discovery mechanisms

Every *_sd_configs block ends up producing the same shape: a list of targets, each with an address and a set of labels prefixed __meta_* that describe where it came from. Those __meta_* labels only exist during relabeling — they are discarded before scraping unless a relabel_configs rule copies their value into a label that survives, which is the whole point of the relabeling stage covered below.

static_configs: a fixed list

The simplest mechanism: a literal list of targets (host:port pairs) and optional labels applied to all of them, no external system involved.

scrape_configs:
  - job_name: node
    static_configs:
      - targets: ["10.0.1.11:9100", "10.0.1.12:9100"]
        labels:
          env: production
      - targets: ["10.0.2.11:9100"]
        labels:
          env: staging

file_sd_configs: targets from a file

Prometheus watches one or more files (JSON or YAML) and reloads the target list whenever they change, with no Prometheus restart or config reload needed. This is the common hand-off point for a configuration-management tool (Ansible, Puppet, Terraform) or a small custom script that writes the file on a cron: the external system owns the inventory, Prometheus just watches for changes.

scrape_configs:
  - job_name: node
    file_sd_configs:
      - files:
          - /etc/prometheus/targets/node/*.json
        refresh_interval: 5m

Each watched file holds a list of target groups:

[
  {
    "targets": ["10.0.1.11:9100", "10.0.1.12:9100"],
    "labels": { "env": "production", "rack": "a3" }
  }
]

Because the file is just data, changing it is the whole deployment. In the lab, orders.json first listed two targets; adding two more entries to the file made them appear in Status > Targets within the five-second refresh_interval, with no reload and no restart. What Prometheus saw for the first target before any relabeling is visible at /api/v1/targets under discoveredLabels:

{
 "__address__": "host.docker.internal:28101",
 "__meta_filepath": "/etc/prometheus/targets/orders.json",
 "__metrics_path__": "/metrics",
 "__scheme__": "http",
 "__scrape_interval__": "5s",
 "__scrape_timeout__": "5s",
 "job": "file-sd",
 "team": "orders",
 "tier": "backend"
}

file_sd contributes one meta label, __meta_filepath; the other __-prefixed labels (__address__, __scheme__, __metrics_path__, the interval and timeout) are the scrape configuration’s own settings exposed so relabeling can change them per target. After the relabel_configs in the lab file ran, the target’s final labels were instance, job, team, tier, owner="orders/backend" and sd_file="orders".

http_sd_configs: targets from an HTTP endpoint

Prometheus polls a URL on refresh_interval and expects back the same target-group JSON shape as file_sd_configs — useful when the source of truth is a live API (a CMDB, an internal inventory service) rather than a file another process writes. The endpoint must set Content-Type: application/json and Prometheus retries with backoff on failure, keeping the last known good list rather than scraping nothing.

scrape_configs:
  - job_name: node
    http_sd_configs:
      - url: http://inventory.internal:8080/prometheus/sd/node
        refresh_interval: 1m

A minimal endpoint is only a few lines. This one, used for the lab’s http-sd job, returns the Pushgateway as a single target group with a source label:

import json
from http.server import BaseHTTPRequestHandler, HTTPServer

TARGETS = [{"targets": ["host.docker.internal:29101"], "labels": {"team": "batch", "source": "inventory-api"}}]

class H(BaseHTTPRequestHandler):
    def do_GET(self):
        body = json.dumps(TARGETS).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.end_headers()
        self.wfile.write(body)
    def log_message(self, *a):
        pass

HTTPServer(("0.0.0.0", 28105), H).serve_forever()

Prometheus scraped host.docker.internal:29101 within one refresh interval and attached source="inventory-api" and team="batch" straight from the response, so the discovered target’s final labels were {instance="host.docker.internal:29101", job="http-sd", source="inventory-api", team="batch"}.

See HTTP-based service discovery for the exact response schema, polling and error-handling semantics, and how it differs from writing your own file_sd_configs output.

Consul, EC2, and Kubernetes SD

Beyond static/file/HTTP, Prometheus ships first-class discovery for a number of specific platforms; each populates its own set of __meta_<mechanism>_* labels reflecting that platform’s metadata.

  • consul_sd_configs queries a Consul catalog for services matching a services filter (or all services when omitted) and exposes Consul tags, node metadata, and health-check state as __meta_consul_* labels — a natural fit when services already register themselves in Consul.

  • ec2_sd_configs lists EC2 instances in a region via the AWS API, exposing instance ID, type, availability zone, VPC, subnet, security groups, and tags as __meta_ec2_* labels — useful for scraping node/agent exporters across an unmanaged or autoscaled fleet without a separate inventory system.

  • kubernetes_sd_configs discovers node, pod, service, endpoints, endpointslice, or ingress objects directly from the Kubernetes API server, exposing pod/service/namespace metadata and annotations as __meta_kubernetes_* labels.

scrape_configs:
  - job_name: consul-services
    consul_sd_configs:
      - server: consul.internal:8500
        services: ["web", "api"]

  - job_name: ec2-nodes
    ec2_sd_configs:
      - region: eu-west-1
        port: 9100

Kubernetes SD is the mechanism most readers of this section actually reach for, and it deserves more than a config snippet — the role you pick (pod vs endpoints vs service, and how each shapes the resulting __meta_kubernetes_* labels) materially changes what gets scraped. That deep dive lives in Containers & Kubernetes Monitoring; this page only establishes that kubernetes_sd_configs exists alongside the other mechanisms above.

relabel_configs: rewriting targets before scraping

relabel_configs runs once per discovered target, before Prometheus scrapes it, against the target’s labels (the job’s own static labels, plus every __meta_* label the discovery mechanism attached). It can drop a target entirely, keep only a matching subset, or rewrite/add labels — including building the final __address__ used to reach the target. Each rule reads one or more source_labels, joins them with separator (default ;), matches the result against regex (default (.*), i.e. "match everything"), and applies action (default replace) using capture groups from that match.

scrape_configs:
  - job_name: kubernetes-pods
    kubernetes_sd_configs:
      - role: pod
    relabel_configs:
      # keep: only pods that opted in via an annotation
      - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
        regex: "true"
        action: keep

      # drop: skip pods still in an init/terminating phase
      - source_labels: [__meta_kubernetes_pod_phase]
        regex: "Pending|Terminating"
        action: drop

      # replace: honor a custom scrape port from an annotation, falling back to 9100
      - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
        separator: ";"
        regex: "([^:]+)(?::\\d+)?;(\\d+)"
        target_label: __address__
        replacement: "${1}:${2}"

      # labelmap: copy every pod label onto the target as a "pod_label_<name>" label
      - regex: __meta_kubernetes_pod_label_(.+)
        action: labelmap

      # replace: surface namespace and pod name as regular labels
      - source_labels: [__meta_kubernetes_namespace]
        target_label: namespace
      - source_labels: [__meta_kubernetes_pod_name]
        target_label: pod

The actions used most often:

Action Effect

keep

Drop the target unless the regex matches source_labels.

drop

Drop the target if the regex matches source_labels.

replace (default)

Set target_label to replacement, with $1/$\{1} etc. substituted from the regex’s capture groups.

labelmap

For every label name matching regex, add a new label named by its capture group, with the same value.

labeldrop / labelkeep

Remove labels matching regex (labeldrop), or remove every label that does not match (labelkeep).

hashmod

Set target_label to hash(source_labels) mod modulus — the basis for sharding targets across multiple Prometheus instances.

Because relabel_configs runs before scraping, it is the only place a target can be dropped without ever being scraped, and the only place __address__ (and therefore the actual host:port Prometheus connects to) can be rewritten. Any label whose name starts with __ is stripped after relabeling finishes and never reaches storage — which is exactly why __meta_* values must be copied into a plain label (as namespace/pod are above) if they need to survive.

Relabeling in the lab: keep, replace and hashmod

The file-sd job of the lab file applies three rules to four targets listed in orders.json:

  • keep with source_labels: [team] and regex: orders|infra discarded the target whose team is batch. Prometheus lists it under droppedTargets (with its discoveredLabels) in /api/v1/targets, which is the place to look when a target you expected is not being scraped.

  • A replace rule with regex: ".*/(.*)\\.json" copied the file’s base name out of __meta_filepath into a new label sd_file (orders).

  • A second replace with two source_labels and separator: "/" built owner="orders/backend" out of the team and tier labels.

Targets that survive end up like this (instance and extra labels shortened):

Target Result Why

:28101 (team=orders)

scraped, owner="orders/backend"

passed the keep regex

:29100 (team=infra)

scraped, owner="infra/host"

passed the keep regex

:29102 (team=infra)

scraped, owner="infra/probe"

passed the keep regex

:29101 (team=batch)

dropped

team does not match the keep regex

Sharding with hashmod. The shard-0 and shard-1 jobs show how several Prometheus servers (or, here, several jobs) split one target list without coordination. Each rule computes hashmod of __address__ and tier modulo 2 into a temporary label, and a following keep retains one value of it. Every target lands in exactly one shard:

shard-0:  host.docker.internal:29101   (tier=gateway)
shard-1:  host.docker.internal:28101   (tier=backend)
          host.docker.internal:29100   (tier=host)
          host.docker.internal:29102   (tier=probe)

The split is by hash, not by count, so it is only even on large target lists; with four targets it came out one to three. The temporary label starts with __, so it disappears after relabeling and costs no storage. Production sharding uses the same rule on each server with its own shard number; see Security & Production Operations.

metric_relabel_configs: rewriting samples after scraping

metric_relabel_configs uses the identical rule syntax — source_labels, separator, regex, action, target_label, replacement — but runs after the scrape completes, against the label set of each returned sample (the metric name is itself matched via the label __name__). It cannot change what gets scraped or how; it only decides what a successful scrape actually stores.

scrape_configs:
  - job_name: node
    static_configs:
      - targets: ["10.0.1.11:9100"]
    metric_relabel_configs:
      # drop: discard a noisy, low-value metric family entirely
      - source_labels: [__name__]
        regex: "node_scrape_collector_duration_seconds"
        action: drop

      # keep: for a job that exposes far more series than needed, keep only a
      # known-useful subset by metric name prefix
      - source_labels: [__name__]
        regex: "node_(cpu|memory|filesystem|network)_.*"
        action: keep

      # replace: normalize a device label's value before it is stored
      - source_labels: [device]
        regex: "veth.*"
        target_label: device
        replacement: "virtual"

The lab measures the effect with the synthetic series every scrape produces, scrape_samples_scraped (what the target returned) against scrape_samples_post_metric_relabeling (what was kept):

Job and rule Scraped Stored Rule

file-sd, target orders-api

41

32

drop of python_gc_.* (9 series removed)

node-lean, node_exporter

1400

172

keep of node_(cpu|memory|filesystem)_.*

file-sd, probe target

59

59

no rule matched

The keep rule shows why that action is dangerous: everything not matching is discarded, including metrics you may need later. up and the scrape_* series are generated after metric relabeling, so they survive even a keep that matches nothing else. The drop is permanent for that scrape: dropped samples are never stored, so unlike a query-time filter it cannot be undone retroactively. The most common use for metric_relabel_configs is cardinality control: dropping metric families or high-cardinality label values (per-request-ID labels, ephemeral container IDs) that would otherwise bloat storage, without asking the target to stop exposing them. Because it runs per sample rather than per target, it is more expensive than relabel_configs at high scrape volume — prefer dropping a whole target earlier, in relabel_configs, when that is an option.

honor_labels: resolving label collisions

A scraped sample can carry a label whose name collides with one Prometheus would otherwise attach from the target (most often instance or job, but any target label can collide). honor_labels (a scrape-config-level boolean, default false) decides who wins:

  • honor_labels: false (the default) — the target’s label wins. A colliding label exposed by the scraped metric is renamed by prefixing it exported_<name>, and the target’s own value is kept under the original name.

  • honor_labels: true — the scraped metric’s label wins outright, overriding the target label of the same name with no renaming.

scrape_configs:
  - job_name: federate
    honor_labels: true
    metrics_path: /federate
    params:
      "match[]": ['{job="node"}']
    static_configs:
      - targets: ["prometheus-leaf:9090"]

The Pushgateway lab (see Exporters & the Pushgateway) shows the difference with real data. The same pushed metric appeared twice, once per scrape job: with honor_labels: true as {instance="db-backup-01", job="nightly_backup"}, and without it as {exported_instance="db-backup-01", exported_job="nightly_backup", instance="host.docker.internal:29101", job="pushgateway-nohonor"}.

honor_labels: true is the right default for federation and for any target scraped through a proxy that must preserve the original instance/job it is reporting on behalf of — see Storage, Federation & Remote Write. For an ordinary application target, leaving it false is almost always what you want: it stops a misbehaving exporter from silently overwriting the instance/job labels Prometheus uses to identify where a series came from. The full semantics, including how it interacts with honor_timestamps, are in Configuration.

Where to next