Automatic Prometheus metrics discovery with Docker labels

Vincent Bernat

Akvo­rado, a net­work flow col­lec­tor, re­lies on Trae­fik, a re­verse HTTP proxy, to ex­pose HTTP end­points for its Docker Com­pose ser­vices. Docker la­bels at­tached to each ser­vice de­fine the rout­ing rules. Trae­fik picks them up au­to­mat­i­cally when a con­tainer starts. In­stead of main­tain­ing a static con­fig­u­ra­tion file to col­lect Prometheus met­rics, we ap­ply the same ap­proach with Grafana Alloy.

Traefik & Docker#

Trae­fik lis­tens for events on the Docker socket. Each ser­vice ad­ver­tises its con­fig­u­ra­tion through la­bels. For ex­am­ple, here is the Loki ser­vice in Akvorado:

services:
  loki:
    # …
    expose:
      - 3100/tcp
    labels:
      - traefik.enable=true
      - traefik.http.routers.loki.rule=PathPrefix(`/loki`)

Once the con­tainer is healthy, Trae­fik cre­ates a router for­ward­ing re­quests match­ing /loki to its first ex­posed port. Colo­cat­ing Trae­fik con­fig­u­ra­tion with the ser­vice def­i­ni­tion is at­trac­tive. How do we achieve the same for Prometheus metrics?

Metrics discovery with Alloy#

Grafana Al­loy, a met­rics col­lec­tor that scrapes Prometheus end­points, in­cludes a discovery.​docker com­po­nent. Just like Trae­fik, it con­nects to the Docker socket.1 With a few re­la­bel­ing rules, we teach it to use Docker la­bels to lo­cate and scrape metrics.

We de­fine three la­bels on each service:

  • metrics.​enable set to true en­ables met­rics col­lection,
  • metrics.​port spec­i­fies the port ex­pos­ing the Prometheus end­point, and
  • metrics.​path spec­i­fies the path to the met­rics endpoint.

If a ser­vice ex­poses more than one port, metrics.​port is manda­tory. Oth­er­wise, it de­faults to the only ex­posed port. The de­fault value for metrics.​path is /metrics. The Loki ser­vice from ear­lier becomes:

services:
  loki:
    # …
    expose:
      - 3100/tcp
    labels:
      - traefik.enable=true
      - traefik.http.routers.loki.rule=PathPrefix(`/loki`)
      - metrics.enable=true
      - metrics.path=/loki/metrics

Al­loy’s con­fig­u­ra­tion is split into four parts:

  1. dis­cover con­tain­ers through the Docker socket,
  2. fil­ter and re­la­bel tar­gets us­ing Docker labels,
  3. scrape the match­ing end­points, and
  4. for­ward the met­rics to Prometheus.

Discovering Docker containers#

The first build­ing block dis­cov­ers run­ning con­tainers:

discovery.docker "docker" {
  host             = "unix:///var/run/docker.sock"
  refresh_interval = "30s"
  filter {
    name   = "label"
    values = ["com.docker.compose.project=akvorado"]
  }
}

This con­nects to the Docker socket and lists con­tain­ers ev­ery 30 sec­onds.2 The filter block re­stricts dis­cov­ery to con­tain­ers be­long­ing to the akvorado project, avoid­ing in­ter­fer­ence with un­re­lated con­tain­ers on the same host. For each dis­cov­ered con­tainer, Al­loy pro­duces a tar­get with la­bels such as __meta_​docker_​container_​label_​metrics_​port for the metrics.​port Docker label.

Relabeling targets#

The re­la­bel­ing step fil­ters and trans­forms raw tar­gets from Docker dis­cov­ery into scrape tar­gets. The first stage keeps only tar­gets with metrics.​enable set to true:

discovery.relabel "prometheus" {
  targets = discovery.docker.docker.targets

  // Keep only targets with metrics.enable=true
  rule {
    source_labels = ["__meta_docker_container_label_metrics_enable"]
    regex         = `true`
    action        = "keep"
  }

  // …
}

The sec­ond stage over­rides the dis­cov­ered port when the ser­vice de­fines metrics.port:

// When metrics.port is set, override __address__.
rule {
  source_labels = ["__address__", "__meta_docker_container_label_metrics_port"]
  regex         = `(.+):\d+;(.+)`
  target_label  = "__address__"
  replacement   = "$1:$2"
}

Next, we han­dle con­tain­ers in host net­work mode. When __meta_​docker_​network_​name equals host, Al­loy rewrites the ad­dress to host.​docker.​internal in­stead of localhost:3

// When host networking, override __address__ to host.docker.internal.
rule {
  source_labels = ["__meta_docker_container_label_metrics_port", "__meta_docker_network_name"]
  regex         = `(.+);host`
  target_label  = "__address__"
  replacement   = "host.docker.internal:$1"
}

The next stage de­rives the job name from the ser­vice name, strip­ping any num­bered suf­fix. The in­stance la­bel is the ad­dress with­out the port:

rule {
  source_labels = ["__meta_docker_container_label_com_docker_compose_service"]
  regex         = `(.+)(?:-\d+)?`
  target_label  = "job"
}
rule {
  source_labels = ["__address__"]
  regex         = `(.+):\d+`
  target_label  = "instance"
}

If a con­tainer de­fines metrics.​path, Al­loy uses it. Oth­er­wise, it de­faults to /metrics:

rule {
  source_labels = ["__meta_docker_container_label_metrics_path"]
  regex         = `(.+)`
  target_label  = "__metrics_path__"
}
rule {
  source_labels = ["__metrics_path__"]
  regex         = ""
  target_label  = "__metrics_path__"
  replacement   = "/metrics"
}

Scraping and forwarding#

With the tar­gets prop­erly re­la­beled, scrap­ing and for­ward­ing are straight­forward:

prometheus.scrape "docker" {
  targets         = discovery.relabel.prometheus.output
  forward_to      = [prometheus.remote_write.default.receiver]
  scrape_interval = "30s"
}

prometheus.remote_write "default" {
  endpoint {
    url = "http://prometheus:9090/api/v1/write"
  }
}

prometheus.​scrape pe­ri­od­i­cally fetches met­rics from the dis­cov­ered tar­gets. prometheus.​remote_​write sends them to Prometheus.

Built-in exporters#

Some ser­vices do not ex­pose a Prometheus end­point. Re­dis and Kafka are com­mon ex­am­ples. Al­loy ships built-in Prometheus ex­porters that query these ser­vices and ex­pose met­rics on their behalf.

prometheus.exporter.redis "docker" {
  redis_addr = "redis:6379"
}
discovery.relabel "redis" {
  targets = prometheus.exporter.redis.docker.targets
  rule {
    target_label = "job"
    replacement  = "redis"
  }
}
prometheus.scrape "redis" {
  targets         = discovery.relabel.redis.output
  forward_to      = [prometheus.remote_write.default.receiver]
  scrape_interval = "30s"
}

The same pat­tern ap­plies to Kafka:

prometheus.exporter.kafka "docker" {
  kafka_uris = ["kafka:9092"]
}
discovery.relabel "kafka" {
  targets = prometheus.exporter.kafka.docker.targets
  rule {
    target_label = "job"
    replacement  = "kafka"
  }
}
prometheus.scrape "kafka" {
  targets         = discovery.relabel.kafka.output
  forward_to      = [prometheus.remote_write.default.receiver]
  scrape_interval = "30s"
}

Each ex­porter is a sep­a­rate com­po­nent with its own re­la­bel­ing and scrape con­fig­u­ra­tion. We set the job la­bel ex­plic­itly since no Docker meta­data can provide it.


With this setup, adding met­rics to a new ser­vice with a Prometheus end­point re­quires only a few la­bels in docker-compose.​yml, just like adding a Trae­fik route. Al­loy picks it up au­to­mat­i­cally. You can ap­ply the same pat­tern with an­other dis­cov­ery method, like discovery.​kubernetes, discovery.​scaleway, or discovery.http. 🩺