Prometheus and PromQL
How Prometheus pulls metrics from targets, how node_exporter exposes a server, and how to answer real questions with PromQL: rates, averages, percentiles and predictions.
By the end of this lesson you'll be able to
0 of 5 completeWhy Prometheus exists
Prometheus is the tool most of this course is built on, so it's worth seeing the problem it was made to solve, one step at a time.
Before: checks that only say OK or CRITICAL
In 2012 a typical team with forty Linux servers ran Nagios. Every few minutes a script logged in to
each box, ran check_disk or check_load, and reported OK, WARNING or CRITICAL. A red square said
the disk was 91% full. It couldn't say since when, how fast it was filling, or whether the other
thirty-nine servers were heading the same way.
The problem: targets come and go
Then the team moved to containers. Containers start and stop every few minutes, each with a new name. Every new one had to be added to the check list by hand, and people forgot. The container that crashed was often the one nobody was watching.
The fix: every target serves its numbers
Prometheus, started at SoundCloud in 2012 and now a CNCF project, flips the model. Each app or
server serves a plain-text page of its current numbers at /metrics. Prometheus visits every
target it knows about on a schedule and collects that page. A target that doesn't answer is
recorded as up = 0, so a dead server is a number you can alert on, not a silence you have to
notice.
How it works: samples become history
Every 15 seconds Prometheus stores each number with its timestamp and keeps them, 15 days by default. With history you ask better questions in its query language, PromQL: not "is the disk full?" but "at this rate, will it be full within 4 hours?".
In this lesson you'll run Prometheus and node_exporter, read what they collect, and write the PromQL you'll use in every dashboard and alert after this.
How Prometheus is built
Prometheus is one server process that does four jobs. Knowing which part does what tells you where to look when something breaks.
- Service discovery works out what to scrape: a fixed list in the config, or a live list from Kubernetes, EC2, Consul or a file.
- The scraper sends
GET /metricsto every target on thescrape_interval. - The TSDB (time series database) writes each sample to local disk. By default it keeps
15 days (
--storage.tsdb.retention.time). Long-term storage across months is a job for add-ons like Thanos or Mimir. - The rule engine evaluates recording rules and alert rules every
evaluation_interval, and sends firing alerts to Alertmanager, a separate program you'll meet in the Alerting stage.
Why pull and not push
In a push system every server sends its numbers to a central collector. If a server dies, it
simply stops sending, and silence is easy to miss. Prometheus pulls, so it knows the full list of
targets it expects. When a scrape fails, it writes up = 0 for that target. A dead server
becomes a number you can alert on.
Pull has one weak spot: a batch job that runs for 20 seconds may finish between two scrapes. For those, the job pushes its final numbers to the Pushgateway (port 9091) and Prometheus scrapes the gateway.
Run Prometheus and node_exporter
Everything in this lesson ran on a lab machine with Prometheus 3.15.1, node_exporter 1.12.1 and Alertmanager 0.34.2, all as Docker containers on one network. Start with a config file:
# prometheus.yml global: scrape_interval: 15s # how often to scrape each target (default is 1m) evaluation_interval: 15s # how often to run rules rule_files: - /etc/prometheus/rules.yml scrape_configs: - job_name: prometheus # Prometheus scrapes its own /metrics too static_configs: - targets: ['localhost:9090'] - job_name: node static_configs: - targets: ['node-exporter:9100'] labels: env: lab # extra label added to every series from this target
Then start both containers on a shared network, so Prometheus can reach node-exporter:9100 by
name:
$ docker network create mon $ docker run -d --name node-exporter --network mon -p 9100:9100 \ --pid host -v /:/host:ro prom/node-exporter --path.rootfs=/host $ docker run -d --name prometheus --network mon -p 9090:9090 \ -v $PWD/prometheus.yml:/etc/prometheus/prometheus.yml:ro \ -v $PWD/rules.yml:/etc/prometheus/rules.yml:ro prom/prometheus
docker network create mondockerbuild and run containersnetworkmanage networkscreatecreate one
docker run -d --name node-exporter --network mon -p 9100:9100 \runstart a new container-drun in the background--name node-exportername the container--network monwhich network to join-p 9100:9100publish a port, host:container\the image to start
docker run -d --name prometheus --network mon -p 9090:9090 \--name prometheusname the container-p 9090:9090publish a port, host:container
--pid host and the read-only mount of / let node_exporter see the host's processes and disks
instead of the container's own. The official guide adds ,rslave to that mount; on Docker inside
WSL that fails with "not a shared or slave mount", so it's left out here. On a real Linux server,
node_exporter usually runs as a plain systemd service instead of a container.
Before you restart Prometheus after an edit, check the files. promtool ships inside the image:
$ docker exec prometheus promtool check config /etc/prometheus/prometheus.yml Checking /etc/prometheus/prometheus.yml SUCCESS: 1 rule files found SUCCESS: /etc/prometheus/prometheus.yml is valid prometheus config file syntax Checking /etc/prometheus/rules.yml SUCCESS: 4 rules found
docker exec prometheus promtool check config /etc/prometheus/prometheus.ymldockerbuild and run containersexecrun a command in a running containerprometheusthe containerpromtool check config /etc/prometheus/prometheus.ymlthe command to run inside it
Scraping and targets
A target is one endpoint Prometheus scrapes, like node-exporter:9100. A job is a group of
targets that do the same thing, like all your node_exporters. Prometheus adds two labels to every
series it scrapes: job (from job_name) and instance (the target's address).
Open Status → Target health (http://localhost:9090/targets). It's the first page to check
when a graph is empty.
For each scrape, Prometheus also writes a few series about the scrape itself:
| Series | Tells you |
|---|---|
up | 1 if the scrape worked, 0 if it failed |
scrape_duration_seconds | How long the scrape took |
scrape_samples_scraped | How many samples the target returned |
$ docker exec prometheus promtool query instant http://localhost:9090 'up' up{instance="alertmanager:9093", job="alertmanager"} => 1 @[1793689704.922] up{instance="localhost:9090", job="prometheus"} => 1 @[1793689704.922] up{env="lab", instance="node-exporter:9100", job="node"} => 1 @[1793689704.922]
docker exec prometheus promtool query instant http://localhost:9090 'up'dockerbuild and run containersexecrun a command in a running containerprometheusthe containerpromtool query instant http://localhost:9090 'up'the command to run inside it
Each line is one series: a metric name plus a unique set of labels. => 1 is its value, and
the number after @ is the evaluation time as a Unix timestamp.
Static lists or service discovery
static_configs is fine for a lab or a handful of fixed servers. Anywhere servers come and go,
use service discovery so Prometheus finds targets itself:
| Config block | Finds targets from |
|---|---|
kubernetes_sd_configs | Pods, services and nodes in a cluster |
ec2_sd_configs | Running EC2 instances, filtered by tags |
file_sd_configs | A JSON or YAML file that another tool keeps updated |
consul_sd_configs | Services registered in Consul |
Discovery returns a lot of metadata (EC2 tags, pod labels). relabel_configs decide which of it
becomes labels, and which targets to drop. A common mistake is keeping too much: every unique
label value creates a new series, and millions of series is how a Prometheus runs out of memory.
Exporters
Your own app can expose /metrics with a Prometheus client library (Go, Python, Java, Node.js
and more). But Linux, MySQL or Nginx don't speak Prometheus. An exporter is a small program
that sits next to them, reads their stats in their own format and serves those stats as a
/metrics page.
node_exporter is the exporter for a Linux machine. It reads /proc and /sys and turns them
into about 700 series: CPU time, memory, disks, filesystems, network and load.
$ curl -s localhost:9100/metrics | grep -vc '^#' 726 $ curl -s localhost:9100/metrics | grep -E 'node_cpu_seconds_total\{cpu="0"|MemAvailable|filesystem_avail_bytes.*mountpoint="/"' # HELP node_cpu_seconds_total Seconds the CPUs spent in each mode. # TYPE node_cpu_seconds_total counter node_cpu_seconds_total{cpu="0",mode="idle"} 6849.66 node_cpu_seconds_total{cpu="0",mode="iowait"} 32.06 node_cpu_seconds_total{cpu="0",mode="irq"} 0 node_cpu_seconds_total{cpu="0",mode="nice"} 0 node_cpu_seconds_total{cpu="0",mode="softirq"} 357.32 node_cpu_seconds_total{cpu="0",mode="steal"} 0 node_cpu_seconds_total{cpu="0",mode="system"} 431.5 node_cpu_seconds_total{cpu="0",mode="user"} 408.4 # HELP node_filesystem_avail_bytes Filesystem space available to non-root users in bytes. # TYPE node_filesystem_avail_bytes gauge node_filesystem_avail_bytes{device="/dev/sdd",device_error="",fstype="ext4",mountpoint="/"} 9.74034223104e+11 # HELP node_memory_MemAvailable_bytes Memory information field MemAvailable_bytes. # TYPE node_memory_MemAvailable_bytes gauge node_memory_MemAvailable_bytes 2.611048448e+09
curl -s localhost:9100/metrics | grep -vc '^#'curlmake an HTTP request-ssilent: no progress bar|pipe: send output to the next commandgrepfind lines that match a pattern-vshow lines that do not match-ccount matching lines
Read it line by line:
# HELPis a human description.# TYPEsays how to treat the numbers.node_cpu_seconds_totalis a counter: total seconds CPU 0 has spent in each mode since boot. It only ever goes up, so the raw value is useless on a graph. You'll always wrap it inrate().node_filesystem_avail_bytesandnode_memory_MemAvailable_bytesare gauges: current values that go up and down.9.74034223104e+11is about 974 GB free on/.- Names end in their unit (
_seconds,_bytes) and counters end in_total. That's the official naming convention, and it makes queries readable.
Other exporters you'll meet: mysqld_exporter, postgres_exporter, redis_exporter, the
blackbox_exporter (probes URLs from outside, like a user would) and kube-state-metrics for
Kubernetes.
node_exporter has no login. Anyone who can reach port 9100 can read your hostnames, disks and network interfaces. Keep exporter ports on a private network or behind a firewall rule that only allows Prometheus.
PromQL: asking questions
PromQL is how you read data out of Prometheus: in the web UI, in Grafana panels and in alert rules. Every query returns one of two shapes:
- an instant vector: one value per series, at one moment (
up), - a range vector: a window of values per series (
up[5m]), which you pass to a function.
You'll build up from simple to useful.
Select series with labels
node_filesystem_avail_bytes{mountpoint="/", fstype!="tmpfs"}
Label matchers are = (equals), != (not equal), =~ (regex match) and !~ (regex doesn't
match). {job=~"node|api"} picks both jobs.
Turn counters into rates
$ promtool query instant http://localhost:9090 'rate(node_network_receive_bytes_total{device="eth0"}[5m])' {device="eth0", env="lab", instance="node-exporter:9100", job="node"} => 48.08771929824561
rate(x[5m]) takes the last 5 minutes of a counter and returns the average per-second
increase: about 48 bytes per second received on eth0. It also handles restarts, when a counter
drops back to 0. increase(x[1h]) is the same idea as a total ("requests in the last hour").
Use a window at least four times your scrape interval (so [1m] or more at 15 s), or the rate
has too few samples and turns jumpy.
Aggregate with sum, avg and by
Here is CPU use as a percentage, the query behind most "CPU" panels:
$ promtool query instant http://localhost:9090 '100 * (1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])))' {instance="node-exporter:9100"} => 9.919298245614039
Inside out: rate(...{mode="idle"}[5m]) is the share of each second each CPU spent idle. avg by (instance) averages all CPUs of one machine and keeps only the instance label. 1 - idle is
busy, and 100 * makes it a percentage: this machine was about 10% busy. sum, min, max,
count and topk(3, ...) work the same way. by (label) keeps those labels, without (label)
drops them.
Percentiles from histograms
Averages hide slow requests (lesson 1). Latency is usually a histogram: a set of
_bucket counters, one per upper bound le ("less than or equal"). Prometheus serves its own HTTP
latency this way:
$ promtool query instant http://localhost:9090 'histogram_quantile(0.95, sum by (le) (rate(prometheus_http_request_duration_seconds_bucket[5m])))' {} => 0.09499999999999999
95% of requests to this Prometheus finished within about 0.095 seconds. The pattern is always the
same: rate of the buckets, sum by (le) (keep le, or the function has nothing to work with),
then histogram_quantile. The result is an estimate: it's only as precise as the bucket bounds.
Match two sides of a division
This query looked right, and returned nothing:
$ promtool query instant http://localhost:9090 'node_load1 / count by (instance) (node_cpu_seconds_total{mode="idle"})' $ promtool query instant http://localhost:9090 'node_load1 / on (instance) count by (instance) (node_cpu_seconds_total{mode="idle"})' {instance="node-exporter:9100"} => 0.625
When you divide two vectors, PromQL pairs up series whose labels are exactly the same. The left
side has instance, job and env. The right side, after count by (instance), has only
instance. No pair matches, so the answer is empty. on (instance) says "match on this label
only". The result, load per CPU core, is 0.625: below 1, so work isn't queueing. An empty result
from a division is almost always this.
Predict the future
$ promtool query instant http://localhost:9090 'predict_linear(node_filesystem_avail_bytes{mountpoint="/"}[1h], 4*3600) / 1e9' {device="/dev/sdd", env="lab", fstype="ext4", instance="node-exporter:9100", job="node", mountpoint="/"} => 963.9708872502385
predict_linear fits a straight line through the last hour and projects it 4 hours ahead: about
964 GB free, so nothing to worry about. When that number goes below 0, the disk fills within 4
hours. That's a far better alert than "disk above 90%", and you'll write it in the Alerting
lesson.
Recording rules
Some queries are expensive and run constantly: a dashboard with ten panels, refreshed every 30 seconds by twenty people. A recording rule runs the query once per evaluation interval and saves the result as a new series:
# rules.yml groups: - name: node rules: - record: instance:node_cpu_utilisation:rate5m expr: 1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m]))
$ promtool query instant http://localhost:9090 'instance:node_cpu_utilisation:rate5m' instance:node_cpu_utilisation:rate5m{instance="node-exporter:9100"} => 0.09919298245614039
The name follows the convention level:metric:operations: aggregated to instance, from
node_cpu_utilisation, using rate5m. Dashboards and alerts now read one small series instead of
recomputing the average over every CPU.
Run two identical Prometheus servers scraping the same targets, so losing one loses nothing. Keep
label values low-cardinality (job, instance, env, status code: yes; user ID, email, full URL:
never). And watch Prometheus itself: prometheus_tsdb_head_series is how many series it holds in
memory.
Answer four questions about your machine with PromQL
With Prometheus and node_exporter running, write one PromQL query for each question, run it, and save the query and its answer: Is every target up? How much memory is available in MB? How busy is the CPU right now in percent? How many bytes per second is the main network interface receiving?
~/promql-answers.txtReveal one safe solution
$ P='docker exec prometheus promtool query instant http://localhost:9090' $ $P 'up' >> ~/promql-answers.txt $ $P 'node_memory_MemAvailable_bytes / 1024 / 1024' >> ~/promql-answers.txt $ $P '100 * (1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])))' >> ~/promql-answers.txt $ $P 'rate(node_network_receive_bytes_total{device="eth0"}[5m])' >> ~/promql-answers.txt $ cat ~/promql-answers.txt
$P 'up' >> ~/promql-answers.txt>>append output to a file
cat ~/promql-answers.txtcatprint a file
On the lab machine the memory query returned 2495.42578125, about 2.4 GB available. Your
numbers will differ; what matters is that every query returns a value and you can say what it
means. If a query is empty, check the label values on the Targets page (your interface may be
ens5 or enp0s3, not eth0).
Try it yourself
0 of 6 steps doneRun each task in your own account or terminal, then tick it off.
Quick check
Prometheus shows up{job="node"} 0. What does it mean?
Official reading for this lesson
- DocsPrometheus overview and architecturePrometheus
- DocsConfiguration (scrape_configs, rule_files)Prometheus
- DocsQuerying basics (PromQL)Prometheus
- DocsPromQL functionsPrometheus
- DocsRecording rulesPrometheus
- GuideMonitoring Linux host metrics with node_exporterPrometheus
- DocsMetric and label namingPrometheus
- GuidePromLabs PromQL cheat sheetPromLabs
Or get every quiz answer right and it completes itself.
Something unclear, wrong or out of date in this lesson? Tell me, and I'll fix it.