Prometheus Service Discovery Explained

Learn how Prometheus service discovery builds scrape targets from Consul, DNS, Kubernetes, EC2, and file configs, with troubleshooting for stale FQDN targets.

Prometheus service discovery sources feeding relabeling rules and a final scrape target address

Contents

Prometheus service discovery is the machinery that keeps scrape targets aligned with infrastructure that keeps moving. Pods roll, EC2 instances come and go, Consul catalog entries change, DNS records move, and a static targets list stops being enough.

The important split is this: service discovery finds possible targets; relabeling turns their metadata into a final __address__; the scrape loop then connects to that address. If you blur those steps, stale target bugs become hard to debug. A target can be present in discovery, correct in /service-discovery, and still fail at scrape time because the final address, DNS resolver, or HTTP connection lifecycle is doing something different.

This guide explains the Prometheus service discovery pipeline, how Consul, DNS, Kubernetes, EC2, file, and static configs differ, and how to troubleshoot the stale FQDN target case without claiming that Prometheus never re-resolves DNS.

What is Prometheus service discovery?

Prometheus service discovery is how Prometheus finds the HTTP endpoints it should scrape without you hardcoding every host and port. A discovery mechanism reads a source of truth, returns target groups with labels, and Prometheus applies relabel_configs before scraping the surviving targets.

A target starts as metadata. Kubernetes discovery might include pod annotations, namespace, pod IP, service name, and labels. Consul discovery might include node address, service address, tags, datacenter, and service metadata. EC2 discovery includes instance ID, private IP, tags, region, and availability zone.

Prometheus then uses relabeling to decide three things:

  • whether to keep or drop the target;
  • what value should become __address__;
  • which metadata should become normal labels such as job, service, cluster, or region.

After relabeling, labels beginning with __meta_ are removed. The final target is what you see on the /targets page.

If you are new to the scrape model, start with our broader Prometheus monitoring guide and the Prometheus overview. This post stays focused on how targets are discovered and turned into scrape addresses.

How the discovery-to-scrape pipeline works

Prometheus has a clean sequence, even when the config looks dense:

  1. A scrape job asks a service discovery mechanism for target groups.
  2. The mechanism returns targets plus __meta_* labels.
  3. relabel_configs run before the scrape.
  4. The final __address__, __scheme__, __metrics_path__, and labels define the target.
  5. The scrape loop sends HTTP requests on scrape_interval.
  6. metric_relabel_configs, if present, run after samples are scraped and before ingestion.
Pipeline showing service discovery sources creating meta labels, relabel configs building __address__, and the scrape loop connecting to the final target
Service discovery and scraping are separate stages. Troubleshooting gets easier when you check each boundary: source of truth, meta labels, relabeling, final address, and scrape connection.

The Prometheus configuration reference documents many discovery mechanisms, including consul_sd_configs, dns_sd_configs, ec2_sd_configs, file_sd_configs, kubernetes_sd_configs, and static_configs. They all feed the same downstream relabeling and scraping pipeline.

This is why relabel_configs are the sharp tool in service discovery setups. They are evaluated before scraping, so they can keep only annotated pods, map cloud tags into labels, rewrite paths, or replace __address__ with a port from metadata. Our Prometheus relabeling guide covers the actions in detail.

Use metric_relabel_configs for a different job: dropping or changing scraped samples after Prometheus already reached the target. They do not affect whether the target is discovered or which address is dialed.

Prometheus service discovery mechanisms compared

Pick a service discovery mechanism based on the source of truth for target membership. The mechanism should match the system that knows which endpoints exist right now.

MechanismSource of truthCommon target addressRefresh behavior to checkGood fit
static_configsYour Prometheus configLiteral host:port entriesConfig reload or restartSmall fixed fleets and local tests
file_sd_configsJSON or YAML target filesWhatever the file writesFile watcher plus refresh fallbackGenerated targets from CMDBs or scripts
consul_sd_configsConsul catalogConsul node or service addressrefresh_interval, default 30s in the docsServices registered in Consul with tags and health metadata
dns_sd_configsDNS recordsNames returned by DNS queriesrefresh_interval, default 30s in the docsDNS-owned target membership, especially SRV records
kubernetes_sd_configsKubernetes APIPod IP, endpoint address, node address, or service metadataWatches Kubernetes API statePods, services, endpoints, nodes, and ingresses
ec2_sd_configsAWS EC2 APIPrivate IP by defaultEC2 API refresh intervalInstances selected by tags, VPCs, regions, or instance state

The table hides one operational detail: a discovery refresh is not the same thing as a new scrape connection. Discovery can say, “this hostname is still a target,” while the scrape client reuses an existing connection or the host resolver returns a cached IP. Keep those layers separate when debugging.

Consul service discovery: catalog data, service addresses, and relabeling

Consul service discovery is useful when service registration, health, tags, and metadata live in the Consul catalog. Prometheus reads Consul and attaches labels such as __meta_consul_address, __meta_consul_service_address, __meta_consul_service, __meta_consul_tags, and __meta_consul_dc. The exact label set depends on the target and Consul data.

A common pattern is to keep services by tag and use the service address as the scrape address:

scrape_configs:
- job_name: "consul-services"
metrics_path: "/metrics"
consul_sd_configs:
- server: "consul.service.consul:8500"
services: ["payments-api"]
refresh_interval: 30s
relabel_configs:
- source_labels: [__meta_consul_tags]
regex: ".*,prometheus,.*"
action: keep
- source_labels: [__meta_consul_service_address, __meta_consul_service_port]
separator: ":"
target_label: __address__
- source_labels: [__meta_consul_service]
target_label: service
- source_labels: [__meta_consul_dc]
target_label: consul_dc

That config assumes __meta_consul_service_address is the endpoint Prometheus should scrape. In many environments it is. In others, Consul stores a stable FQDN, a proxy address, or a service name that resolves through internal DNS.

When Consul returns an FQDN, make the choice visible in labels:

relabel_configs:
- source_labels: [__meta_consul_service_address]
target_label: discovered_name
- source_labels: [__meta_consul_service_address, __meta_consul_service_port]
separator: ":"
target_label: __address__

Keeping discovered_name lets alerts say which stable service name is unhealthy even if instance changes later. It also helps you compare /targets, /service-discovery, DNS lookups, and application logs during an incident.

For HashiCorp-specific scraping setup, see our guide to Vault, Consul and Nomad monitoring. That post covers Consul’s own Prometheus metrics endpoint. This one is about using Consul to discover arbitrary Prometheus scrape targets.

DNS service discovery: when DNS should be the target source of truth

Use DNS service discovery when DNS records define the target set. Prometheus DNS SD can query record types including A, AAAA, MX, NS, and SRV, depending on how you configure it. The configuration reference lists refresh_interval for dns_sd_config with a default of 30 seconds.

A simple DNS SD job looks like this:

scrape_configs:
- job_name: "dns-srv-services"
dns_sd_configs:
- names:
- "_metrics._tcp.apps.internal.example.com"
type: SRV
refresh_interval: 30s
relabel_configs:
- source_labels: [__meta_dns_name]
target_label: dns_name

DNS SD is different from putting a hostname in static_configs or writing an FQDN into __address__ from Consul. With DNS SD, DNS is the discovery source. Prometheus periodically queries DNS for the target list. With an FQDN in __address__, another discovery mechanism owns the target list, and DNS is used later when the scrape client opens a network connection.

That distinction matters for stale target incidents. If DNS owns membership, prefer DNS SD. If Consul owns membership and merely stores hostnames, use Consul SD, but know that the scrape layer still has to resolve and connect to those names.

DNS caches can sit in several places: the host resolver, systemd-resolved, NodeLocal DNSCache, CoreDNS, a corporate recursive resolver, or a language/runtime-level cache inside a proxy. A fresh dig against one resolver does not prove the scraper is using the same answer.

Our DNS monitoring guide covers DNS record health and resolver behavior from the DNS side. For Prometheus, add the scrape target view to that picture.

EC2 and Kubernetes service discovery patterns

EC2 and Kubernetes service discovery are the common choices when infrastructure APIs own the target list.

For EC2, Prometheus discovers instances from the AWS API and exposes metadata labels for relabeling. A typical job keeps running instances with a monitoring tag, uses the private IP, and copies tags into stable labels:

scrape_configs:
- job_name: "ec2-node-exporter"
ec2_sd_configs:
- region: us-west-2
port: 9100
filters:
- name: instance-state-name
values: [running]
- name: tag:PrometheusMonitoring
values: [enabled]
relabel_configs:
- source_labels: [__meta_ec2_private_ip]
target_label: __address__
replacement: "$1:9100"
- source_labels: [__meta_ec2_tag_Name]
target_label: instance_name
- source_labels: [__meta_ec2_availability_zone]
target_label: az

If you use vmagent for EC2 discovery, our docs show how to enable EC2 service discovery with vmagent. The same design question applies: choose the field that represents the real scrape endpoint, then keep cloud identity as labels.

Kubernetes discovery reads the Kubernetes API. The most common pattern is annotation-based pod scraping:

scrape_configs:
- job_name: "kubernetes-pods"
kubernetes_sd_configs:
- role: pod
relabel_configs:
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
action: keep
regex: "true"
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
action: replace
target_label: __metrics_path__
regex: "(.+)"
- source_labels: [__meta_kubernetes_pod_ip, __meta_kubernetes_pod_annotation_prometheus_io_port]
separator: ":"
target_label: __address__
- source_labels: [__meta_kubernetes_namespace]
target_label: namespace
- source_labels: [__meta_kubernetes_pod_name]
target_label: pod

Kubernetes has its own service discovery model for application traffic. Our Kubernetes service discovery guide explains Services, Endpoints, and DNS inside the cluster. Prometheus Kubernetes SD is related, but it is Prometheus reading Kubernetes objects to build scrape targets.

Troubleshooting stale FQDN targets in Prometheus

A public Prometheus issue reported a stale FQDN target with Consul SD: Consul supplied a hostname, the backing CNAME moved, DNS lookups returned the new IP, but Prometheus kept scraping an old endpoint. Maintainer discussion separated Consul discovery from scrape behavior and pointed at layers such as HTTP connection reuse, reverse proxies, and DNS caching rather than treating it as proof that Prometheus never resolves DNS again.

That is the right diagnostic posture. Frame the symptom as: “Prometheus is still reaching the old endpoint after the name changed.” Then prove which layer is stale.

Troubleshooting flow for a stale Prometheus FQDN target: compare targets, service discovery output, DNS lookup, resolver cache, keep-alive connection, and reload options
Check the layers in order: discovery output, final target labels, DNS from the same host, DNS caches, then connection reuse confirmed in access logs. Use a reload only as a diagnostic.

Start with the Prometheus UI and APIs:

  • /service-discovery shows what the SD mechanism returned before relabeling.
  • /targets shows the final target after relabeling, including __address__ as instance.
  • Target labels show whether you are scraping an IP, an FQDN, or an unexpected host:port.

Then compare DNS from the same network path Prometheus uses:

# Run on the Prometheus host or in the Prometheus pod.
getent hosts metrics-api.internal.example.com
dig +short metrics-api.internal.example.com
dig @<cluster-dns-ip> +short metrics-api.internal.example.com

If Prometheus runs in Kubernetes, test from a debug pod in the same namespace and node pool. If it runs on EC2, test on the EC2 host. The resolver path matters.

Next, look for connection reuse. The Go HTTP client resolves a hostname when it opens a new network connection. If an existing keep-alive connection remains usable, a scrape can keep using that connection without a fresh DNS lookup. The issue discussion includes this as the suspected root cause for the reported Prometheus 3.10.0 case, with proposed fixes that were still under review at the time of that discussion.

Practical tests:

  • Check the target’s access logs for Prometheus requests hitting the old host or old backend.
  • Temporarily reload Prometheus and see whether the target recovers.
  • Temporarily restart Prometheus only as a diagnostic, not as the steady-state fix.
  • Lower upstream keep-alive limits or close idle connections at the proxy to see whether recovery follows.
  • Check DNS cache TTLs and resolver behavior on the Prometheus host or cluster.

Avoid the unsafe shortcut: “Prometheus does not re-resolve DNS for discovered targets.” The safer statement is: Prometheus may keep reaching an old endpoint when the final scrape address is an FQDN and connection reuse or DNS caching prevents a fresh dial from seeing the new answer.

Config patterns that avoid stale or misleading targets

The best fix is usually to reduce indirection in __address__ and keep identity in labels.

If Consul owns endpoint membership and stores real endpoint IPs, scrape those IPs and keep the service name separately:

relabel_configs:
- source_labels: [__meta_consul_service_address, __meta_consul_service_port]
separator: ":"
target_label: __address__
- source_labels: [__meta_consul_service]
target_label: service
- source_labels: [__meta_consul_node]
target_label: consul_node

If DNS owns membership, use DNS SD rather than putting a DNS name into another discovery system:

scrape_configs:
- job_name: "dns-owned-targets"
dns_sd_configs:
- names: ["_metrics._tcp.apps.internal.example.com"]
type: SRV
refresh_interval: 30s

If Kubernetes owns membership, use pod, endpoints, or service discovery roles instead of scraping a stable in-cluster service name for every backend. Scraping individual pods gives you per-pod health and avoids hiding one bad pod behind a ClusterIP.

If you must scrape a stable FQDN, document that choice:

  • keep the stable name as a label;
  • record the resolver path Prometheus uses;
  • set proxy keep-alive behavior intentionally;
  • make reload and restart procedures safe;
  • alert on target health with service identity intact.

This turns a vague “target down” page into an actionable incident: which service name, which final address, which resolver, which proxy, and which scrape job.

Alerting guardrails for discovered targets

The built-in up metric remains the first alert for target reachability, but service discovery needs labels that make the page useful.

A basic alert often starts like this:

groups:
- name: scrape-health
rules:
- alert: PrometheusTargetDown
expr: up == 0
for: 5m
labels:
severity: page
annotations:
summary: "Prometheus target down for {{ $labels.job }} {{ $labels.instance }}"
description: "Target labels: service={{ $labels.service }}, cluster={{ $labels.cluster }}, namespace={{ $labels.namespace }}"

That alert is only as good as your labels. Consul targets should preserve service and datacenter. Kubernetes targets should preserve namespace, pod, app, and cluster. EC2 targets need instance ID, instance name, region, and availability zone. DNS targets need the DNS name that generated the target.

Tune discovery refresh intervals with the source API in mind. A shorter interval can reduce recovery time, but it also increases load on Consul, the Kubernetes API, AWS APIs, or DNS. The right value is part of the reliability budget for your monitoring system.

Finally, treat Prometheus reloads as an operational path. Prometheus supports configuration reloads with SIGHUP or the /-/reload endpoint when lifecycle reloads are enabled. A reload should be safe, observable, and documented before the day a stale target incident forces someone to improvise.

How Last9 fits when Prometheus target sets keep growing

Prometheus service discovery solves target churn, not metric volume by itself. Once Kubernetes, EC2, Consul, and DNS jobs all land in one estate, the next failure mode is usually cardinality: every pod, instance, service, zone, and deployment label multiplies the series count.

If you remote write Prometheus metrics to Last9, our Prometheus integration docs cover the supported ingestion path. For high-cardinality control, the Last9 Control Plane can drop, remap, redact, forward, and aggregate at ingest, and previews every rule against live data before you save it, as documented in the Control Plane docs.

That does not replace clean service discovery. It gives you a place to manage the telemetry stream after targets are discovered and scraped.

FAQ

What is Prometheus service discovery?

Prometheus service discovery is the part of Prometheus that finds scrape targets from systems such as Kubernetes, Consul, DNS, EC2, file-based target lists, and static configs. It returns target labels, then relabeling decides which targets remain and what address Prometheus scrapes.

How does Prometheus service discovery work?

A service discovery mechanism refreshes target groups from its source of truth, Prometheus attaches meta labels, relabel_configs keep, drop, or rewrite those labels, and the scrape loop connects to the final __address__ on the configured interval. Discovery changes the target list; scraping collects metrics from the selected targets.

How often does Prometheus refresh Consul service discovery targets?

The Prometheus configuration reference lists refresh_interval for consul_sd_config with a default of 30 seconds. That refresh reads Consul catalog data again. It does not mean every scrape opens a new TCP connection or bypasses DNS caches.

Does Prometheus re-resolve DNS for scrape targets on every scrape?

Not necessarily. DNS is involved when the scrape client opens a new network connection for a hostname. If an existing HTTP keep-alive connection is reused, or a host or cluster DNS cache returns an old answer, the scrape can continue to hit an old endpoint. Treat stale FQDN targets as a scrape-layer and DNS-cache troubleshooting problem, not only a service discovery problem.

Should I use DNS service discovery or Consul service discovery?

Use DNS service discovery when DNS records are the source of truth for target membership. Use Consul service discovery when the Consul catalog owns service registration, health, tags, and service metadata. If Consul returns FQDNs, keep the stable name as a label and be deliberate about what becomes __address__.

About the authors
Nishant Modak

Nishant Modak

Founder at Last9. Loves building dev tools and listening to The Beatles.

Last9 logo and enter key

See Last9 in action.

OpenTelemetry · Prometheus

Just update your config. Start seeing data on Last9 in seconds.

Datadog · New Relic · Others

We've got you covered. Bring over your dashboards & alerts in one click.

Built on Open Standards

100+ integrations. OTel native, works with your existing stack.