Prometheus: Service Discovery
Service discovery is Prometheus finding its scrape targets from a live source instead of a fixed list. Hard-coded targets do not scale.
Write a targets file
The file lists one target and a label. Any program can rewrite this file when services change.
cat > targets.json <<'EOF'
[{"targets": ["127.0.0.1:18105"], "labels": {"job": "shopsentry-file", "env": "lab"}}]
EOFPoint a job at the file
The file_sd_configs block replaces the static list. Prometheus re-reads the file by itself.
cat >> prometheus.yml <<'EOF'
- job_name: shopsentry-file
file_sd_configs:
- files: ['targets.json']
EOFCheck the config, then reload
The same check and reload as before. Discovery needs no new flags.
promtool check config prometheus.yml && curl -s -X POST http://127.0.0.1:19105/-/reload; echo "reload $?"Example
curl -s "http://127.0.0.1:19105/api/v1/query?query=up%7Bjob%3D%22shopsentry-file%22%7D"Key points
- Service discovery: Prometheus asks a source where the targets are, on every refresh.
- A static list in prometheus.yml works for three targets and breaks for three hundred.
- Every new service means editing the file, reloading, and hoping nobody mistyped a port.
- File-based discovery reads a JSON file of targets, so another tool can write that file.
- The file can carry labels too, such as env lab, which land on every series.
- DNS discovery finds targets from DNS records, which suits services that move.
- Kubernetes discovery watches the cluster API and finds pods and services as they appear.
- Discovery refreshes on its own, so a new target is scraped without a reload.
In this example, the target from targets.json is scraped and healthy, with up at 1. The env label from the file rides along on the series, exactly as written. Nothing in prometheus.yml names the ShopSentry address any more, so adding a second service is now a file edit, not a config reload.
Note
Discovery finds targets. It does not check they are healthy. The up metric still does that job.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
Your fleet grows from 3 services to 300. Why does a static target list in prometheus.yml stop working well?