Bookmarks
ReferenceDevOps & cloudVerified

Prometheus and Grafana

Prometheus and Grafana are a metrics collection system and dashboards for monitoring services. This reference covers exporters, PromQL, alerting rules, Alertmanager and dashboards.

checked 6 Nov · next check 13 Nov · 63 min read

Sections
12
Reading
63 min
Current version
3.15.1
Written from
prometheus.io/docs

Check status of the reference

Verified 6 Nov · next check 13 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What Prometheus and Grafana are and how they work

Prometheus is a monitoring system with its own time series database: the server polls targets over HTTP, stores samples and runs queries over them. Grafana provides dashboards and alerts on top of data sources, and for this pair the main data source is Prometheus.

Prometheus collects numeric metrics, such as web server response time, the number of active database connections or memory in use. Each metric is stored with a timestamp and labels, which are name–value pairs used to filter it: job="api", instance="web1". The model is pull: Prometheus fetches values from targets itself, and the application is unaware of it.

How the pair works together

Each target serves its metrics as text over HTTP at /metrics, either from the application itself (with a client library) or from a separate exporter. Prometheus polls targets at a fixed interval (once a minute by default), stores the samples, each a value with a timestamp, in its TSDB and evaluates rules: some compute new series, others fire alerts. Alerts go to Alertmanager, which sends them on to receivers.

A single Prometheus server is autonomous: the database, rules and queries are all in it.

Components

ComponentWhat it does
Prometheus serverpolls targets, stores series in the TSDB, evaluates rules and answers PromQL queries
Exportersexpose metrics for things that have no /metrics of their own: the Linux kernel, PostgreSQL, nginx
Client librariescounters and timers in application code, serving /metrics
Pushgatewayaccepts metrics from short-lived jobs so that Prometheus can scrape them later
Alertmanagerdeduplicates, groups and routes alerts to receivers
Grafanadashboards and alerts on top of Prometheus and other data sources

Most components are written in Go and shipped as static binaries: unpack and run. The exception is client libraries, which are packages for the application’s language. Many components are optional; the minimum is a single Prometheus server.

A minimal set of targets

The Prometheus server needs targets. List them in the prometheus.yml config statically or find them through service discovery. A typical pair is prometheus (itself) and a host metrics exporter on each server:

yamlprometheus.yml
global:  scrape_interval: 15s scrape_configs:  - job_name: prometheus    static_configs:      - targets: ["localhost:9090"]   - job_name: node    static_configs:      - targets: ["web1:9100", "web2:9100"]

What each exporter provides and how to add your own is covered in the section “Collecting metrics and exporters”; the full query language is in the section “The PromQL query language”.

What Alertmanager does

Alertmanager is a separate service, and Prometheus sends it alerts over HTTP. It deduplicates repeats, groups similar alerts into a single email or message and routes them to receivers according to rules: email, Telegram, PagerDuty. It is also where you configure silences for maintenance windows.

yamlalertmanager.yml (excerpt)
route:  receiver: mail receivers:  - name: mail    email_configs:      - to: admin@example.com  - name: tg    telegram_configs:      - bot_token: change-me        chat_id: 123456789

Why Grafana

Prometheus has graphs, but dashboards are built in Grafana. It connects to Prometheus as a data source, requests metrics through PromQL and draws graphs, tables and charts. One dashboard can combine panels from several data sources, and template variables substitute host names into queries, so the same dashboard works for staging and production. Grafana can also send alerts itself, but pick one place for them, usually Alertmanager.

When Prometheus fits and when it does not

Prometheus is designed for numeric time series: metrics of machines, services and applications, including dynamic microservice environments. Each server is autonomous and does not depend on network storage, so you can rely on it when everything else has already broken.

  • Fits: service load and errors, request latency, disk and queue capacity.
  • Does not fit: billing and anything that needs every single event to be exact, because time-based sampling may miss individual values.
  • Does not replace: logs, which belong to Loki and similar systems (see the section “Storage: TSDB and remote write”), or traces, which belong to distributed tracing.

What to know beforehand

  • HTTP and response codes: metrics are scraped over HTTP; see the HTTP and REST reference, sections on methods and status codes.
  • The Linux command line: processes, services, firewall; see the Linux reference.
  • YAML syntax: the Prometheus and Alertmanager configs are written in it.

Section sources

the section is written from these pages

Cheat sheet: PromQL and commands

A cheat sheet of PromQL queries and Prometheus commands: target availability, rates and errors, host resources, latency percentiles, configuration checks and the HTTP API. Replace the metric, job and label names in the examples with your own.

Target status

For every scrape target Prometheus stores an up series: 1 after a successful scrape and 0 after a failed one. In the web UI, the “Table” tab shows instant queries and “Graph” shows range queries.

TaskQuery
Targets that do not respond to scrapingup == 0
Number of unreachable targetscount(up == 0)
Share of successful scrapes over 15 minutesavg_over_time(up[15m]) * 100
Duration of the last scrapescrape_duration_seconds
Samples per scrapescrape_samples_scraped
Targets of one jobup{job="node"}

Rates and errors

With counters, apply the aggregation after rate(): only then can the calculation detect a counter reset when a target restarts.

TaskQuery
HTTP request rate over 5 minutesrate(http_requests_total[5m])
The same, summed by jobsum by (job) (rate(http_requests_total[5m]))
5xx errors over 5 minutesincrease(http_requests_total{status=~"5.."}[5m])
The three busiest seriestopk(3, rate(http_requests_total[5m]))
Instant rate from the last two samplesirate(http_requests_total{job="api-server"}[5m])

Host resources

Host metrics come from the node_exporter exporter, and their names start with node_. CPU and network metrics are counters (names with the _total suffix), while memory and filesystem metrics are gauges.

TaskQuery
CPU usage, %100 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100
CPU time in system mode per secondrate(node_cpu_seconds_total{mode="system"}[1m])
Available memorynode_memory_MemAvailable_bytes
Memory in use, %(1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) * 100
Free space on filesystemsnode_filesystem_avail_bytes
Incoming traffic per secondrate(node_network_receive_bytes_total[1m])

Latency (histograms)

histogram_quantile() calculates a percentile from a classic histogram, a metric with _bucket, _sum and _count series.

TaskQuery
95th percentile of request latencyhistogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))
Percentile by jobhistogram_quantile(0.95, sum by (job, le) (rate(http_request_duration_seconds_bucket[5m])))
Average latencyrate(http_request_duration_seconds_sum[5m]) / rate(http_request_duration_seconds_count[5m])
Observations per secondrate(http_request_duration_seconds_count[5m])

Configuration checks

TaskCommand
Check the configurationpromtool check config prometheus.yml
Check a rules filepromtool check rules alert.rules.yml
Run unit tests for rulespromtool test rules rules_test.yml
Run a query from the command linepromtool query instant http://localhost:9090 'up'
Reload the config (--web.enable-lifecycle flag)curl -X POST http://localhost:9090/-/reload

HTTP API

The stable API lives under /api/v1, and responses are JSON with a status field. An error in the expression returns code 422, and a query timeout returns 503.

TaskCommand
Instant querycurl 'http://localhost:9090/api/v1/query?query=up'
Status of all targetscurl http://localhost:9090/api/v1/targets
Loaded rulescurl http://localhost:9090/api/v1/rules
Active alertscurl http://localhost:9090/api/v1/alerts
Label namescurl http://localhost:9090/api/v1/labels
Values of the job labelcurl http://localhost:9090/api/v1/label/job/values
Series matching a selectorcurl -g 'http://localhost:9090/api/v1/series?' --data-urlencode 'match[]=up'
Current server configcurl http://localhost:9090/api/v1/status/config
TSDB snapshot (--web.enable-admin-api flag)curl -XPOST http://localhost:9090/api/v1/admin/tsdb/snapshot
basha long query via POST
curl -X POST http://localhost:9090/api/v1/query \  --data-urlencode 'query=count(up == 0)'

Section sources

the section is written from these pages

Installation and first run

A minimal monitoring setup is built from three services: the Prometheus server collects metrics, the node_exporter exporter exposes host metrics, and Grafana draws graphs. Each service is installed separately, and the finished setup is checked on the Targets page and with the up query.

Prometheus: the binary

The Prometheus project publishes ready-made binaries for Linux, macOS and Windows on the download page, prometheus.io/download. Put the version into the archive URL yourself, since new releases come out every six weeks. The archive unpacks into a directory containing the prometheus binary and an example config, prometheus.yml:

bashon the server
wget https://github.com/prometheus/prometheus/releases/download/\v3.16.0/prometheus-3.16.0.linux-amd64.tar.gztar xvfz prometheus-3.16.0.linux-amd64.tar.gzcd prometheus-3.16.0.linux-amd64

The example config in the archive already scrapes Prometheus itself: the server exposes its own metrics like any other target, so it can collect and watch itself. The config structure is simple: global sets the scrape interval for all jobs, and each entry in scrape_configs is a job, a group of targets that the server polls under one name:

yamlprometheus.yml
global:  scrape_interval: 15s scrape_configs:  - job_name: prometheus    static_configs:      - targets: ["localhost:9090"]

Start the server and open http://localhost:9090 after a few seconds; the UI is available straight away. By default the collected data is stored in the data/ subdirectory of the working directory, and the --storage.tsdb.path flag changes the path. The server’s own metrics are served at http://localhost:9090/metrics:

bashin the archive directory
./prometheus --config.file=prometheus.yml

Prometheus in Docker

The image is called prom/prometheus, and one command starts the server with the example config on port 9090. Supply your own config as a bind mount and keep the data in a named volume so that it survives recreating the container. The image takes the same command-line flags as the binary, added after the image name:

bashon the host
docker volume create prometheus-datadocker run -d --name prometheus \  -p 9090:9090 \  -v $(pwd)/prometheus.yml:/etc/prometheus/prometheus.yml \  -v prometheus-data:/prometheus \  prom/prometheus:v3.16.0

node_exporter for host metrics

An exporter is a service that turns system readings into Prometheus metrics. node_exporter exposes CPU load, memory, disks and network of a Linux host. It is a single static binary from an archive on the same download page, and it listens on port 9100:

bashon the monitored server
wget https://github.com/prometheus/node_exporter/releases/download/\v1.12.1/node_exporter-1.12.1.linux-amd64.tar.gztar xvfz node_exporter-1.12.1.linux-amd64.tar.gzcd node_exporter-1.12.1.linux-amd64./node_exporter

Check the metrics with an HTTP request: curl http://localhost:9100/metrics prints a long list, and you are looking for lines with the node_ prefix. In the Prometheus config, add a node job with the exporter’s address:

yamlprometheus.yml (addition)
  - job_name: node    static_configs:      - targets: ["localhost:9100"]

In a container, the exporter sees only the container itself by default, not the host. Give it the host’s network and process namespaces (--net=host, --pid=host) and the host’s filesystem root mounted at /host, together with the --path.rootfs flag:

bashon the host
docker run -d --name node-exporter \  --net=host --pid=host \  -v /:/host:ro,rslave \  quay.io/prometheus/node-exporter:v1.12.1 \  --path.rootfs=/host

Grafana: the APT repository

Grafana OSS is installed on Debian and Ubuntu from the apt.grafana.com repository, so updates arrive with apt upgrade. Download the repository key, add the repository to the APT sources and install the package:

bashon a Debian or Ubuntu server
sudo apt-get install -y apt-transport-https wget gnupgsudo mkdir -p /etc/apt/keyringswget https://apt.grafana.com/gpg-full.keysudo mv gpg-full.key /etc/apt/keyrings/grafana.ascsudo chmod 644 /etc/apt/keyrings/grafana.ascecho "deb [signed-by=/etc/apt/keyrings/grafana.asc] https://apt.grafana.com stable main" \  | sudo tee /etc/apt/sources.list.d/grafana.listsudo apt-get updatesudo apt-get install grafana

The package creates the grafana user and the grafana-server service. Enable it at boot and start it:

bashon the server
sudo systemctl daemon-reloadsudo systemctl enable grafana-server.servicesudo systemctl start grafana-server

Grafana in Docker

The image is called grafana/grafana, and the port inside the container is 3000. Grafana keeps users, dashboards and data sources in a built-in database in /var/lib/grafana, so a named volume is needed here too:

bashon the host
docker run -d --name grafana \  -p 3000:3000 \  -v grafana-storage:/var/lib/grafana \  grafana/grafana:13.3

First sign-in and the data source

Grafana opens at http://localhost:3000. For the first sign-in, the username and password are both admin; after signing in, Grafana prompts you to set a new password.

A data source is a connection to Prometheus with its address. In the menu on the left, open Connections → Add new connection, select Prometheus and enter the address http://localhost:9090. If Grafana and Prometheus run in different containers, localhost inside Grafana is its own container, so use the service name from Compose, for example http://prometheus:9090. When the “Save & test” button answers “Successfully queried the Prometheus API”, the data source works.

Checking: Targets and the up query

Target status is shown on the Status → Target health page (http://localhost:9090/targets): each target is marked UP or DOWN, with the time of the last scrape. For every target Prometheus stores the automatic up metric: 1 if the scrape succeeded and 0 if the target did not respond. If a target is DOWN, check whether the exporter is listening on its port on the monitored machine; troubleshooting is covered in the section “Common errors and troubleshooting”:

bashon the Prometheus server
curl http://localhost:9100/metrics | head -5curl 'http://localhost:9090/api/v1/query?query=up'
CheckCommand or pageWhat you see
Exporter metricscurl localhost:9100/metricsraw node_… lines
Server targetsStatus → Target healthUP or DOWN, scrape time
Target metricthe up query1 for success, 0 for no response

All three services in Compose

On one machine the services can be combined in a single Compose file; volumes, networks and startup rules are described in the Docker reference, section “Docker Compose”. The exporter runs in the host’s network namespace (network_mode: host), so Prometheus and Grafana find each other by service names, while the exporter is reached by the host’s address: in prometheus.yml, set the node target to host.docker.internal:9100, not localhost:9100:

yamlcompose.yaml
services:  prometheus:    image: prom/prometheus:v3.16.0    ports:      - 9090:9090    extra_hosts:      - host.docker.internal:host-gateway    volumes:      - ./prometheus.yml:/etc/prometheus/prometheus.yml      - prometheus-data:/prometheus  node-exporter:    image: quay.io/prometheus/node-exporter:v1.12.1    network_mode: host    pid: host    command:      - --path.rootfs=/host    volumes:      - /:/host:ro,rslave  grafana:    image: grafana/grafana:13.3    ports:      - 3000:3000    volumes:      - grafana-storage:/var/lib/grafanavolumes:  prometheus-data:  grafana-storage:

Section sources

the section is written from these pages

Metrics: data model and types

A Prometheus metric is a time series: a stream of timestamped values with one name and one set of labels. The type (counter, gauge, histogram or summary) is chosen when you write the code, and it determines how the metric is queried later.

A series is defined by the metric name and labels, which are pairs such as method="GET". A single value in a series is a sample: a number with a timestamp accurate to the millisecond. Changing the value of any label (a different response code, a different handler) creates a new series, because every label set is stored separately.

texttext exposition format
# HELP http_requests_total The total number of HTTP requests.# TYPE http_requests_total counterhttp_requests_total{method="GET",code="200"} 1027http_requests_total{method="GET",code="400"} 3

In the text exposition format, the # HELP line with the description and the # TYPE line with the type come before the first samples. Without a # TYPE line the type is untyped. A metric name consists of letters, digits, _ and :, a label name of the same without the colon, and label values are quoted.

The four metric types

TypeWhat it measuresExampleHow to query
countera monotonically increasing count: requests, errors, completed jobs; resets to zero on restarthttp_requests_totalrate(http_requests_total[5m]) for the rate over a window
gaugea value that goes up and down: memory, queue depth, number of active requestsmyapp_queue_depththe value itself, avg_over_time, max_over_time
histograma distribution of observations: request durations, response sizeshttp_request_duration_secondshistogram_quantile(), the average from _sum and _count
summaryquantiles precomputed in the application, plus the sum and count of observationsrpc_duration_secondsready-made {quantile="0.95"} series, the average from _sum and _count

A counter can only increase, so you calculate its rate with the rate() function. Anything that can decrease belongs in a gauge: current memory, temperature, the number of concurrent requests. The number of running processes does not suit a counter, because it goes down.

promqlqueries on a counter and a gauge
# counter: the rate of growth, not the value itselfrate(http_requests_total[5m]) # gauge: the value as is and the five-minute averagemyapp_queue_depthavg_over_time(myapp_queue_depth[5m])

Histogram or summary

Both a histogram and a summary describe a distribution of observations. Both expose the number of observations, _count, and their sum, _sum, from which the average is calculated. The difference is in the quantiles: a summary computes them in advance inside the application for the configured φ values and a sliding window, whereas a histogram exposes buckets with le boundaries and the histogram_quantile() function calculates the quantile on the server.

A φ-quantile is the value below which a fraction φ of observations lie: the 0.95 quantile is the 95th percentile. Summary quantiles cannot be aggregated: the average of percentiles from several replicas is meaningless. If a service is replicated and you need an overall 95th percentile, use a histogram, since its buckets can be summed. After release you cannot add a new quantile or window to a summary, because they are baked into the code.

promql95th percentile from a histogram
# classic histogram: a quantile from bucketshistogram_quantile(0.95,  sum by (le) (rate(http_request_duration_seconds_bucket[5m]))) # native histogram: buckets are aggregated into a single serieshistogram_quantile(0.95,  sum(rate(http_request_duration_seconds[5m])))

A native histogram stores all buckets in a single sample: one time series instead of dozens of _bucket series, with higher resolution and no need to configure buckets in advance. Exposition requires the protobuf format, and for now only the Go and Java client libraries support it. The server can convert a classic histogram into a native one on its side (NHCB).

How to name metrics

A metric name is built from the application prefix, the subject and the unit of measurement in base units, such as seconds and bytes. Write the unit in the plural at the end of the name, and give an accumulating counter an additional _total suffix. Do not include a label name in the metric name: after aggregating by that label it becomes meaningless.

RuleExample
the unit goes at the end of the name, in base units: seconds, byteshttp_request_duration_seconds, node_memory_usage_bytes
an accumulating counter takes the _total suffixhttp_requests_total
the prefix is the application or library namemyapp_queue_depth
do not repeat a label name in the metric namemyapp_requests{method="GET"}

How metrics reach Prometheus is covered in the section “Collecting metrics and exporters”; queries are covered in full in the section “The PromQL query language”.

Section sources

the section is written from these pages

Scraping and exporters

Prometheus polls (scrapes) targets — HTTP endpoints that expose metrics — and stores the samples in its database. The scrape_configs sections of prometheus.yml set what to scrape and how often; an exporter exposes the metrics of programs that cannot do it themselves.

The configuration starts with a global section holding the defaults: a scrape_interval of 1m and a scrape_timeout of 10s. Each entry in scrape_configs is a job: a set of targets that share scraping rules. A job can override the interval and timeout, but the timeout must not exceed the interval.

yamlprometheus.yml
global:  scrape_interval: 15s  scrape_timeout: 10s scrape_configs:  - job_name: prometheus    static_configs:      - targets: ['localhost:9090']   - job_name: api    scrape_interval: 5s    metrics_path: /metrics    scheme: http    static_configs:      - targets: ['192.0.2.11:8000', '192.0.2.12:8000']        labels:          env: prod

Prometheus fetches metrics_path (/metrics by default) from each target using the scheme, either http or https. Labels from labels in static_configs are attached to every metric of the target.

job, instance and the up series

A scraped address is an instance, usually a single process; a group of instances with the same purpose is a job. Prometheus adds the labels job (from job_name) and instance (from the target address) to the metrics; if they clash with labels in the exposed data, honor_labels decides which wins.

For every scrape Prometheus records auxiliary series. The main one is up: 1 if the target responded, 0 if the scrape failed; use it to check target availability. The series scrape_duration_seconds and scrape_samples_scraped show how long the scrape took and how many samples it returned. A target that responds without any metrics yields up = 1 and no samples.

The path of a sample: from a job through two relabeling filters to the database

Service discovery

Targets in static_configs are written by hand. When there are many of them and they change, service discovery supplies the list: it asks the infrastructure for targets and attaches __meta_* labels to them, from which relabeling builds the target address and the labels you need. There are several dozen mechanisms, including Consul, EC2 and GCE; the full list is in the scrape_configs description.

MechanismWhere targets come fromWhen to choose it
static_configsa list in prometheus.ymla handful of targets, all under your control
file_sd_configsYAML or JSON files with a list of targets; changes are picked up immediatelya script or an operator writes the target list
kubernetes_sd_configsthe Kubernetes API: nodes, pods, services, endpointsa Kubernetes cluster
docker_sd_configsDocker Engine: containers and their portsa test bench or a host running Docker
yamldiscovery from files
  - job_name: node    file_sd_configs:      - files: ['/etc/prometheus/targets/*.yml']

Relabeling

Relabeling rewrites a label set in steps, in the order they are written. relabel_configs works on targets before the scrape: it filters them out and sets the address and scheme. metric_relabel_configs works on metrics after the scrape, as the last step before they are written to the database; it does not affect auxiliary series such as up.

ActionWhat it does
replacethe default: joins the values of source_labels with ;, matches them against regex and writes replacement, with groups such as ${1}, to target_label
keepkeeps targets whose joined labels match regex
dropdrops targets whose joined labels match regex
labelmapcopies the values of labels whose names match regex to new label names
labeldropremoves labels whose names match regex

The regular expression is matched against the whole joined string: to find a substring, wrap it in .*, as in .*substring.*. Labels with the __ prefix are internal and are removed after relabeling, so copy any value you need into an ordinary label with target_label.

yamlthe two kinds of relabeling
    relabel_configs:      # keep containers labelled scrape=true      - source_labels: [__meta_docker_container_label_scrape]        regex: true        action: keep      # env label taken from the container label      - source_labels: [__meta_docker_container_label_env]        target_label: env    metric_relabel_configs:      # drop debugging metrics      - source_labels: [__name__]        regex: 'go_.*|process_.*'        action: drop

Exporters

An exporter translates the metrics of a third-party system into the Prometheus format: it queries the system itself and serves the result at /metrics. The Prometheus organisation maintains the official exporters; the catalogue on the website is grouped by topic — databases, hardware, HTTP, storage.

What to monitorExporterWhere it gets metrics
A Linux host: CPU, memory, disk, networkNode/system metrics exporter (official)the /proc and /sys files
An HTTP endpoint: response code and timeBlackbox exporter (official)a request to the target itself: HTTP, HTTPS, DNS, TCP, ICMP
PostgreSQLPostgreSQL exporterqueries to pg_stat_*
MySQLMySQL server exporter (official)SQL queries to system tables
Kafka, CassandraJMX exporterJMX beans of the JVM application

An exporter listens on its own port: node_exporter on 9100, blackbox_exporter on 9115. The blackbox exporter is a good illustration: the sites to check are listed as targets, and relabeling passes each target to the exporter itself as the target parameter.

yamlnode_exporter and blackbox
  - job_name: node    static_configs:      - targets: ['192.0.2.10:9100', '192.0.2.11:9100']   - job_name: blackbox-http    metrics_path: /probe    params:      module: [http_2xx]    static_configs:      - targets: ['https://example.com']    relabel_configs:      - source_labels: [__address__]        target_label: __param_target      - source_labels: [__param_target]        target_label: instance      - target_label: __address__        replacement: '127.0.0.1:9115'

Metrics for your own application

Instrument your own code with a client library: official ones exist for Go, Java, Python, Ruby, Node.js and Rust. The library serves the current values of all registered metrics over HTTP; metric types are covered in the section “Metrics: data model and types”.

pythonthe prometheus_client library
from prometheus_client import Counter, start_http_serverimport randomimport time REQUESTS = Counter(    "myapp_requests",    "Requests handled",    ["method", "code"],) if __name__ == "__main__":    # metrics server in a background thread    start_http_server(8000)    while True:        REQUESTS.labels("GET", "200").inc()        time.sleep(random.random())

After start_http_server(8000) the metrics are served at /metrics — all that remains is to add the application’s address with port 8000 to the targets. Name the counter without the _total suffix: the library appends it when exposing the metric.

Applying a new configuration

The configuration is reloaded without a restart: send the process a SIGHUP signal or a POST request to /-/reload (the latter works when the --web.enable-lifecycle flag is set). An invalid configuration is not applied and the previous one keeps running, so check the file beforehand with promtool check config.

bashon the Prometheus host
kill -HUP "$(pgrep -f prometheus)"# or over HTTP when --web.enable-lifecycle is oncurl -X POST http://localhost:9090/-/reloadpromtool check config prometheus.yml

Section sources

the section is written from these pages

PromQL query language

A PromQL query is built from three parts: a selector picks series by metric name and labels, rate() turns a counter into a per-second rate, and an aggregator such as sum by (job) combines series. The result is a set of values at the moment of the query.

promqlthe reference query
# requests per second handled by api-serversum by (job) (  rate(http_requests_total{job="api-server"}[5m]))

Read the query from the inside out: the selector http_requests_total{job="api-server"} picks the counter series of the api-server job, the [5m] window selects the samples of the last five minutes, rate() computes the per-second increase, and sum by (job) collapses the series of all the job’s targets into one line.

What a query returns

A PromQL expression evaluates to one of four types: three are used in practice and are listed in the table; the fourth, string, is reserved and not used in queries. A range query accepts only a scalar or an instant vector as the root, so a range vector is an intermediate value: you feed it to rate() or avg_over_time().

TypeWhat it containsWhere it is needed
instant vectorone sample per series at the query timethe result of almost any query
range vectorthe samples of each series over a window, for example [5m]input to rate() and avg_over_time()
scalara single number without labelsliterals such as 2 and 0.9; comparing scalars requires bool

An instant query is evaluated at a single point in time; a range query is a series of instant queries at equal steps from the start to the end of the range. The language syntax is the same in both cases.

Selectors and labels

Select a series by name and labels: http_requests_total{job="api-server",code=~"5.."}. The label operators are = (exactly equal), != (not equal), =~ (matches the regular expression) and !~ (does not match it). Regular expressions are fully anchored: code=~"5.." means ^5..$. A matcher against an empty string (code="") also selects series that have no code label at all. A selector must contain a metric name or at least one matcher that does not match the empty string — {job=~".*"} is rejected.

promqlfilter, window, offset
http_requests_total{job="api-server"}http_requests_total{job="api-server",code=~"5.."}http_requests_total{job="api-server"}[5m]http_requests_total{job="api-server"} offset 1hrate(http_requests_total{job="api-server"}[5m] offset 1w)

Without a window, a selector returns the newest sample that is no more than five minutes old — this is the lookback delta, which the --query.lookback-delta flag changes. offset shifts the selection into the past and goes immediately after the selector: sum(m offset 5m) is correct, sum(m) offset 5m is an error.

The rate of a counter

A counter only grows and resets to zero when the process restarts — metric types are covered in the section “Metrics: data model and types”. rate(x[5m]) divides the counter’s increase over the window by the window length in seconds and returns the average per-second increase; it handles resets and missed scrapes on its own. irate(x[5m]) uses the last two samples — good for volatile graphs, but use rate for alerts. increase(x[5m]) is the same as rate multiplied by the window length in seconds: the number of events in the window. Put the aggregator outside the function — sum(rate(...)) — otherwise a reset after a target restarts goes unnoticed.

rate() divides the counter’s increase over the window by the window length; a reset on restart is accounted for.

The window must contain at least two samples, otherwise a rate cannot be computed. Make the window at least four times the scrape interval: with a 15 s interval that is one minute, and in practice [5m] is more common — twenty samples, enough margin even for several missed scrapes in a row.

Aggregation

Aggregators collapse an instant vector into a smaller one. without removes the listed labels and keeps the rest; by does the opposite and keeps only the listed ones — this is how series are grouped: sum by (job) gives one line per job, and sum without (instance) sums the targets within each combination of the remaining labels.

AggregatorWhat it does
sumthe sum of the values
avgthe average
min, maxthe minimum and maximum
countthe number of series in the group
topk(k, …)the k largest series with their labels
promqlaggregators with by and without
# sum per job: target labels are droppedsum by (job) (rate(http_requests_total[5m])) # average across targets within each jobavg without (instance) (rate(http_requests_total[5m])) # the three series with the highest ratetopk(3, rate(http_requests_total[5m]))

Vector matching

The binary operators + - * / % ^ combine two instant vectors or a vector and a scalar; with a scalar the operation is applied to every series, while between vectors the metric name __name__ is dropped. Two vectors are matched on their labels: by default all labels must match, on(a, b) restricts matching to the listed labels, and ignoring(a, b) excludes the listed ones. When one side has several series per group, you need the group_left or group_right modifier, pointing to the “many” side.

Comparisons == != > < >= <= filter by default: only series for which the condition is true remain. The bool modifier changes this — each series gets 1 or 0. The logical operators and, or and unless intersect, merge and subtract sets of series by their labels.

promqlvector matching
# one to one: share of 500 errors per targetrate(http_requests_total{code="500"}[5m])  / ignoring(code)  sum without (code) (rate(http_requests_total[5m])) # many to one: one series per code on the leftsum by (job, method, code) (rate(http_requests_total[5m]))  / on (job, method) group_left  sum by (job, method) (rate(http_requests_total[5m]))

Percentiles and subqueries

histogram_quantile(φ, …) extracts a percentile from a histogram — which series a histogram produces is covered in the section “Metrics: data model and types”. For a classic histogram the argument is rate() over the _bucket series; the le label holds the bucket boundary and must be kept in the result, so include it in by when aggregating.

promqla percentile and a subquery
# 90th percentile per job: le must be in byhistogram_quantile(0.9,  sum by (job, le) (    rate(http_request_duration_seconds_bucket[10m]))) # maximum rate over an hour in one-minute stepsmax_over_time(rate(http_requests_total[5m])[1h:1m])

The subquery expr[1h:1m] runs an instant query at a series of steps within the window and returns a range vector; the step can be omitted, in which case the global evaluation interval is used (one minute by default). Every step is a separate query, so write a subquery only when the selector window cannot give you the range vector you need.

Rules and alerts are built from the same expressions — see the section “Alerting rules and Alertmanager” — as are dashboard graphs, covered in the section “Grafana dashboards”.

Section sources

the section is written from these pages

Alerting rules and Alertmanager

Alerting in Prometheus has two layers: alerting rules evaluate a PromQL condition and raise the alarm, and Alertmanager groups alerts, silences repeats and delivers notifications to the right people without noise.

Both kinds of rules, recording rules and alerting rules, live in YAML files that rule_files in prometheus.yml points to. A file is a list of groups: within a group, rules run sequentially at the same point in time. The group’s evaluation interval is set by interval; without it, global.evaluation_interval is used. A SIGHUP signal reloads the files without a restart, provided all of them are valid.

Rules for heavy queries

A recording rule evaluates an expensive query in advance and stores the result as a new time series. Dashboards and alerting rules then read the ready-made metric without recomputing it. A recording rule’s name must be a valid metric name; keep the colon in metric names for recording rules — see the section “Metrics: data model and types”.

yamlrules.yml — two rules in one group
groups:  - name: latency    interval: 30s    rules:      - record: job:http_latency:mean5m        expr: sum by (job) (rate(http_requests_seconds_sum[5m]))          / sum by (job) (rate(http_requests_seconds_count[5m]))       - alert: HttpLatencyHigh        expr: job:http_latency:mean5m > 0.5        for: 5m        keep_firing_for: 5m        labels:          severity: page        annotations:          summary: "Mean latency {{ $value }} s on {{ $labels.job }}"

Rules in a group run in order: the recording rule above prepares the metric and the alerting rule reads it. keep_firing_for keeps an alert in the firing state for the given time after its condition stops being true, which protects against flapping. Without it, the alert resolves on the first evaluation where the condition is false.

Alert states

The result of expr is a set of label sets, and each one becomes a separate alert. While the condition is false, the alert is inactive. The for clause requires the condition to hold for the given time: until it expires the alert is pending, then it becomes firing. labels adds labels to the alert and overwrites labels with the same name; annotations holds a description for the on-call engineer.

The path of an alert: from the first true evaluation to the notification
StateWhat it meansWhat you see in Prometheus
inactivethe condition is false or the rule has not been evaluated yetnothing: there is no series
pendingthe condition is true, the for interval has not yet expiredthe ALERTS{alertstate=...} series equals 1, the Alerts tab
firingthe interval has expired, the alert has been sent to Alertmanagerthe ALERTS{alertstate=...} series equals 1, the Alerts tab
resolvedthe condition has become falsethe series disappears; Alertmanager can report the resolution

Label and annotation values are Go templates: $labels.job inserts the value of a label, $value inserts the computed number, and humanize formats it readably. A template runs on every iteration of the rule, so keep it light.

Alertmanager: routes and receivers

Prometheus sends firing alerts to Alertmanager over HTTP: the addresses are set in alerting.alertmanagers, either statically or through service discovery. Every alert enters the root route, which matches everything; child routes tell alerts apart with matchers. An alert stays in the first matching route, or with continue: true is also checked against the following routes; parameters that are not set are inherited from the parent.

yamlalertmanager.yml — routing by severity
route:  receiver: mail  group_by: [job, alertname]  group_wait: 30s  group_interval: 5m  repeat_interval: 4h  routes:    - receiver: oncall      matchers:        - severity="page"      group_wait: 10s receivers:  - name: mail    email_configs:      - to: team@example.com  - name: oncall    webhook_configs:      - url: http://oncall.example.com/hook
ParameterDefaultWhat it does
group_by—which labels to group alerts by; ['...'] disables grouping
group_wait30show long to wait before the first notification; an alert that resolves sooner is not sent
group_interval5mthe pause between notifications for an existing group
repeat_interval4hthe pause before a repeat if nothing in the group has changed
continuefalsewhether to check the following routes after a match
mute_time_intervals—names of the time intervals during which the route is silent

Inhibition and silences

Inhibition mutes some alerts while others are active. A rule consists of source and target matchers: while the source is active, targets with the same values of the equal labels stay silent. An alert about a node mutes that node’s warnings.

yamlalertmanager.yml — inhibition
inhibit_rules:  - source_matchers:      - severity="critical"    target_matchers:      - severity="warning"    equal: [instance]

A silence hides notifications during maintenance or for an incident that has already been dealt with. Create one in the Alertmanager web interface or with the amtool command; the rules keep running, but no notifications are sent.

Alert on symptoms

Prometheus best practices advise alerting on symptoms that users feel rather than on possible causes: look for causes on dashboards once a symptom has raised the alarm. A slow component at the bottom of the stack is not an alert while overall latency is normal; alert on latency and errors at the top of the stack.

  • every alert requires action: if there is nothing to do, it is not an alert but a dashboard;
  • symptoms are what users see: errors and latency at the top of the stack, data lag in offline processing, a batch job that has not run for a long time;
  • leave some margin: a brief flap should not wake the on-call engineer, which is what for and keep_firing_for are for;
  • failures that users do not see but that are costly deserve a separate alert;
  • meta-monitoring: an alert that the whole path from Pushgateway through Prometheus to Alertmanager and email works is more reliable than checking each link.

Checks before deployment

bashon the Prometheus host
# before committing and reloadingpromtool check rules rules.ymlpromtool test rules rules_test.ymlamtool check-config alertmanager.yml

promtool check rules checks the syntax without starting a server. promtool test rules runs unit tests: fixtures with series and the expected alerts. amtool check-config checks the Alertmanager configuration and warns about incompatibility with the strict UTF-8 label parsing that Alertmanager is moving to.

Grafana Alerting or Alertmanager

Grafana Alerting can also evaluate conditions. A rule is not limited to Prometheus: several data sources can be combined in one rule, and notifications use contact points and policies. Choose it for conditions that span different sources or for alerts on a dashboard panel.

For infrastructure alerts, rules in Prometheus are usually the better choice: the YAML file sits in a repository, passes a promtool check before deployment and does not depend on Grafana. If an alert is configured but never reaches the recipient, see the section “Common errors and troubleshooting”.

Section sources

the section is written from these pages

Grafana dashboards

A Grafana dashboard is a set of panels: each panel runs a query against a data source and draws the response in the chosen way. This section shows how to build a clear dashboard from Prometheus metrics and keep it as code, in YAML and JSON files, rather than as clicks in the interface.

The Prometheus data source is built into Grafana — you do not install it separately. In its settings you give the server address, for example http://prometheus:9090 with Docker Compose. The key setting is “Scrape interval” in the “Interval behavior” group: the interval at which Prometheus collects samples (15 s by default). Set it to the same value as in prometheus.yml, because rate() calculations depend on it. The same page selects the query editor: “Builder” assembles a query from blocks, “Code” is a text editor for PromQL.

yamlprovisioning/datasources/prometheus.yaml
apiVersion: 1datasources:  - name: prometheus    type: prometheus    uid: prometheus    url: http://prometheus:9090    isDefault: true    jsonData:      timeInterval: 15s      httpMethod: POST

What a dashboard consists of

A dashboard is stored as a JSON model: a panel knows its grid position gridPos, its query and its visualisation type, and variables substitute values into queries. Time is set for the whole dashboard: one time range at the top controls all panels, so graphs can be compared with one another.

A dashboard reads metrics from Prometheus and is itself stored as code.

Which visualisation to use

Choose the visualisation type by the question the panel answers. Prometheus metrics are time series, so most panels are graphs over time; the other types reduce a series to a number or a table.

What to showVisualisation
How a value changed over time: traffic, load, durationTime series
The current value as a single number: active sessions, queue lengthStat
The same number against a limit: disk usage, memoryGauge
Many values at once, broken down by label: a list of scrape targetsTable
The distribution of values over time: request durations from a histogramHeatmap

A panel takes units from the metric automatically, but check them: “None” instead of “seconds” gives graphs without an axis, and a double rate() gives meaningless “operations per second per second”. Set colour thresholds (“Thresholds”) in the same units as the values.

Dashboard variables

A template variable turns a dashboard from a picture of one server into a tool for all of them: the values appear in a list at the top, and your choice changes every panel at once. Take the list of values from the data’s labels: the “Label values” type with the label job returns all values of job; in the classic syntax the same query is written as label_values(up, job).

promqla panel query
sum by (handler) (  rate(http_requests_total{job=~"$job"}[$__rate_interval]))

In the [...] window of rate() and increase(), use $__rate_interval rather than a fixed 5m or $__interval: Grafana calculates the window from the scrape interval and guarantees at least four samples, so the graph does not fall apart when the zoom changes. For the calculation to be correct, the data source’s “Scrape interval” must match the real scrape interval: if Prometheus scrapes every 60 s while Grafana keeps the default 15 s, rate() returns nothing.

Importing ready-made dashboards

For typical scenarios — Node Exporter, PostgreSQL, Kubernetes — you do not write dashboards from scratch: the library on grafana.com holds thousands of ready-made ones, each with an ID. Importing by ID takes a minute:

  1. Open the menu “Dashboards → New → Import dashboard”.
  2. Paste the ID or URL of a dashboard from grafana.com, or a JSON file.
  3. Set the name, the folder and the UID, the dashboard’s unique identifier.
  4. Select your own data source in place of the one the author used.
  5. Click “Import” and check that the panels find their metrics.

Dashboards as code: provisioning

Dashboards made by hand live in the Grafana database and disappear when the container is recreated. Provisioning solves this the same way as for a data source: on startup Grafana reads a directory of YAML and JSON files and creates or updates dashboards from them. Keep the files in git next to the configuration.

yamlprovisioning/dashboards/dashboards.yaml
apiVersion: 1providers:  - name: dashboards    type: file    updateIntervalSeconds: 30    allowUiUpdates: false    options:      path: /var/lib/grafana/dashboards

The dashboards themselves — JSON files with panels — sit at this path. Environment variables ($ENV_VAR_NAME or ${ENV_VAR_NAME}) are substituted in the YAML provisioning files; substitution does not work in the dashboard JSON files themselves.

jsondashboards/node-overview.json
{  "title": "Node overview",  "uid": "node-overview",  "tags": ["node"],  "refresh": "30s",  "schemaVersion": 16,  "panels": []}

Practices: RED and USE

Two methods define what a dashboard contains. RED describes a service: request rate, errors and duration — three graphs for each handler. USE describes a resource: utilisation, saturation and errors — three graphs for a disk, a CPU or a network. Build a service dashboard from RED and a node dashboard from USE.

PanelPromQL query (simplified)
Request raterate(http_requests_total[$__rate_interval])
Error ratiosum(rate(...{status=~"5.."})) / sum(rate(...))
Median durationhistogram_quantile(0.5, rate(...[$__rate_interval]))

Ready-made dashboards are often overloaded: hundreds of graphs, of which five are useful. Start with a small RED set for the main service and USE for nodes; move “just in case” panels to a separate dashboard. An overly broad query sum(rate(...)) with no breakdown hides the degradation of a single instance — add by (instance).

Do not configure alerts in dashboards: a person looks at graphs, while rules send alerts — see the section “Alerting rules and Alertmanager”. The full query language is covered in the section “PromQL query language”, and empty graphs and other problems in the section “Common errors and troubleshooting”.

Section sources

the section is written from these pages

Storage: TSDB and remote write

Prometheus writes the samples it scrapes to a local time series database (TSDB), and PromQL queries run against it. The retention setting controls how much data is kept, and remote write sends samples beyond the local disk to external storage.

Inside the TSDB, data is stored in 2-hour blocks. Incoming samples first go to the head block, which is held in memory and protected by a write-ahead log (WAL) on disk: after a crash the server restores the data by replaying the WAL. Every 2 hours the head block is closed and written to disk as a directory with chunks, an index and metadata. Background compaction then merges the 2-hour blocks into larger ones, up to 10% of the retention period or 31 days, whichever is smaller.

How data flows through the local TSDB; remote write runs in parallel.

How much disk space metrics need

The TSDB stores a sample in 1–2 bytes on average, so disk space is estimated as retention time in seconds × ingested samples per second × bytes per sample. To reduce the volume, scrape fewer time series or increase the scrape interval; cutting the number of series is more effective, because compression works within a single series.

bashestimating disk space, on your own machine
# 15 days, 10,000 samples per second, 2 bytes per sampleecho $(( 15 * 24 * 3600 * 10000 * 2 ))

With these numbers the result is 25,920,000,000 bytes, about 26 GB. The formula gives a lower bound: the WAL and the buffer needed for compaction add to it, so leave headroom on the disk.

Retention: time or size

Set the retention time with the --storage.tsdb.retention.time flag and the size limit with --storage.tsdb.retention.size. If neither is set, data is kept for 15 days by default. When both are set, whichever limit is reached first applies. The storage.tsdb.retention block in the configuration file accepts the same values; it overrides the flags (which are marked deprecated in the configuration) and is reloaded without a restart.

yamlprometheus.yml
# prometheus.yml — overrides the flags of the same namestorage:  tsdb:    retention:      # keep 30 days of history      time: 30d      # block size limit — for a 50 GB disk      size: 40GB
FlagWhat it setsDefault
--storage.tsdb.pathTSDB data directorydata/
--storage.tsdb.retention.timehow long samples are kept15d
--storage.tsdb.retention.sizesize limit for blocksdisabled
--web.enable-admin-apiadmin API: snapshots and series deletiondisabled

The retention.size limit includes both the WAL and the head chunks (chunks_head), but only completed blocks are deleted. Set the limit to no more than 80–85% of the disk: during compaction the source blocks and the new block exist side by side, and without a buffer the disk fills up sooner. Expired blocks are deleted in the background.

Remote write and remote read

Remote write sends every received sample over HTTP to a compatible store, so data survives the loss of the server and outlives the local retention period. The protocol is protobuf compressed with snappy; specification 1.0 is stable, 2.0 is still experimental, and the server supports both. write_relabel_configs filters which series are sent.

yamlprometheus.yml
remote_write:  - url: https://ingest.example.com/api/v1/write    # send only node metrics    write_relabel_configs:      - source_labels: [__name__]        regex: 'node_.*'        action: keep

Remote read is the mirror operation: at query time Prometheus fetches raw series from the remote end by selector and time range, and evaluates all of PromQL itself, so read scale is limited by the capacity of a single server. Prometheus becomes a receiver when started with --web.enable-remote-write-receiver, which accepts samples on /api/v1/write. For a list of compatible long-term storage systems, see the Integrations page of the Prometheus documentation.

Federation

Federation is a way to pass data between Prometheus servers: one server scrapes the /federate endpoint of another and receives the current values of the selected series, with selectors listed in match[] parameters. This is how a top-level server collects aggregated metrics from lower-level ones, or one service’s server pulls what it needs from a neighbour. Federation cannot transfer history, because /federate returns only current values; for history, use remote write.

yamlprometheus.yml, on the scraping server
scrape_configs:  - job_name: federate    honor_labels: true    metrics_path: /federate    params:      match[]:        - '{job="prometheus"}'        - '{__name__=~"job:.*"}'

Snapshots with the admin API

Snapshots are created by the admin API: enable the --web.enable-admin-api flag and send a POST request to /api/v1/admin/tsdb/snapshot. The server copies the blocks to the snapshots/ directory inside the data directory, and that directory can then be backed up. Copying the data directory without a snapshot risks losing the samples written after the last block, since blocks are created every 2 hours. The WAL directories (wal/, chunks_head/ and wbl/) are excluded from the copy: without them the snapshot is consistent, at the cost of losing the range covered by the WAL.

bashon the Prometheus server
curl -XPOST http://localhost:9090/api/v1/admin/tsdb/snapshot

Section sources

the section is written from these pages

Monitoring security

The metrics and HTTP interfaces of Prometheus and Grafana are designed for a trusted network: by default Prometheus requires neither authentication nor encryption, and Grafana accepts the admin/admin login over HTTP. Monitoring exposed to the internet hands every metric to a stranger, and, through exporters, gives them a path into the server’s internal network.

Who Prometheus trusts

The Prometheus security model assumes that whoever reads the HTTP interface and the logs is a trusted party: such a user sees every time series in the database and the debugging information. Only a trusted administrator should be able to change the configuration, rules and startup parameters. Prometheus does not treat metrics as secrets: anything an exporter collects from an application is visible to anyone who can reach the HTTP interface.

This leads to the main rule: do not publish the HTTP interfaces of Prometheus components to the internet. That includes the exporters’ /metrics, the APIs of server components and /pprof. Requests to these paths can easily overload a server into denial of service.

TLS and passwords on Prometheus itself

Prometheus enables its own authentication and HTTPS through a web configuration file: the --web.config.file flag points to a YAML file that is re-read on every HTTP request, so changes and new certificates take effect immediately, without a restart. Passwords in the basic_auth_users section are stored as bcrypt hashes, not as plain text. The same scheme works for Alertmanager and most exporters; credentials for scraping are set with a basic_auth block in prometheus.yml.

bashon the monitoring server
# python3-bcrypt package (Debian/Ubuntu) or pip install bcryptpython3 -c 'import getpass, bcrypt; \print(bcrypt.hashpw(getpass.getpass("password: ").encode(),                    bcrypt.gensalt()).decode())' # validate the web configurationpromtool check web-config web.yml
yamlweb.yml
tls_server_config:  cert_file: /etc/prometheus/tls.crt  key_file: /etc/prometheus/tls.key basic_auth_users:  admin: $2y$12$a7HliPIm4Zioj0BuvvoQQOnNFSNdubXFtzMTmDb0rdLFrdcoowtbm
bashstarting with a web configuration
prometheus \  --config.file=/etc/prometheus/prometheus.yml \  --web.config.file=/etc/prometheus/web.yml

Dangerous flags

Two flags open management interfaces that are closed by default. --web.enable-admin-api enables the admin API under /api/*/admin/, including deletion of time series. --web.enable-lifecycle opens /-/reload and /-/quit, which reload the configuration and stop the process over HTTP. Enable them only together with a web configuration and a firewall: without protection, anyone who can reach the port can stop monitoring or erase data.

What it exposesPathDefault
admin API: deleting series/api/*/admin/disabled
reload and shutdown/-/reload, /-/quitdisabled
exporter metrics/metricsopen inside the network

Exporters: a closed service network

Most exporters answer the same fixed set of requests and have nothing to change over HTTP, but /metrics is still not meant for the internet: scraping can be overloaded, and the responses reveal how the server is built, including disk, service and version names. Exporters such as Blackbox and SNMP take their target from URL parameters: someone who reaches them can make them connect anywhere, and together with the passwords stored in them, a secret can leak.

  • Open metrics ports on 127.0.0.1 or on a dedicated monitoring network
  • Allow access in the firewall only from the monitoring server
  • Expose only Grafana to the outside, behind a reverse proxy with TLS
  • Do not enable honor_labels: a target could then pass itself off as another target

Grafana: login and roles

The first Grafana Admin is created on first start with the default password admin; change it before the server goes on the network. Set permanent values with the admin_user and admin_password settings in the [security] section, or with the GF_SECURITY_ADMIN_USER and GF_SECURITY_ADMIN_PASSWORD variables before the first start. Disable anonymous access and self-registration (both are off by default) with enabled = false in the [auth.anonymous] section and allow_sign_up = false in [users].

inigrafana.ini
[security]admin_user = adminadmin_password = change-me [users]allow_sign_up = false [auth.anonymous]enabled = falseorg_role = Viewer

The Viewer role has more power than it seems: a Viewer can send the data source any query of their own, not just the one drawn on the dashboard. Restrict access to the underlying database with a separate account with narrow permissions. Share dashboards “for everyone to view” through public dashboards or a separate organisation, not through anonymous access: anonymous access makes every dashboard available by link and opens the API for listing folders and data sources.

The secret_key setting in [security] encrypts data source passwords in the Grafana database. Change it only together with re-encrypting the data: changing it without re-encryption leaves the stored passwords unreadable. Keep the key together with the database backup: without it, the backup cannot restore data source passwords.

Secrets in prometheus.yml

Move passwords and tokens out of prometheus.yml into separate files: use password_file instead of password and credentials_file instead of credentials. Keep the secret file readable only by the user the process runs as. Prometheus does not expose secret configuration fields in logs or the HTTP interface. Secrets taken from the environment, such as cloud keys for service discovery, have no such protection: the place where they are stored may itself be exposed, so do not leave them in publicly readable files and variables.

yamlprometheus.yml
scrape_configs:  - job_name: node    basic_auth:      username: prometheus      password_file: /etc/prometheus/secrets/node.password    static_configs:      - targets: ["10.0.0.15:9100"]

Bad and good

bashthe wrong way
# don’t do this: metrics and Grafana exposed, admin/admin loginprometheus \  --web.enable-admin-api \  --web.enable-lifecycle \  --web.listen-address=0.0.0.0:9090 # Grafana on 0.0.0.0:3000, default password not changed
bashthe right way
# the right way: TLS and a password, management paths closedprometheus \  --config.file=/etc/prometheus/prometheus.yml \  --web.config.file=/etc/prometheus/web.yml \  --web.listen-address=127.0.0.1:9090
  • The HTTP interfaces of Prometheus and exporters stay on a closed network
  • Only Grafana faces outward, behind a reverse proxy with TLS; Prometheus is protected by the password from web.yml
  • --web.enable-admin-api and --web.enable-lifecycle only with protection in place
  • The Grafana admin password is changed before the server goes on the network, and anonymous access is off
  • Scraping secrets live in *_file files, not in the configuration text

For TLS certificates and keys, see the “TLS and PKI” reference, section “X.509 certificates”; for the server’s own firewall, see the “Linux server hardening” reference, section “Firewall”.

Section sources

the section is written from these pages

Common errors and troubleshooting

Follow the chain “target → Prometheus → Grafana”: check an empty query in Prometheus itself first, and only then look for the cause in Grafana. Most often the culprit is a target that does not respond, or a mismatched scrape interval.

Order of checks

  1. Status → Target health: a target in the DOWN state, with the error text of the last scrape;
  2. the up query on the “Table” tab: 1 after a successful scrape, 0 after a failed one;
  3. the server log: the scrape error text and any refusal to apply the configuration;
  4. promtool check config: validates the configuration before a reload;
  5. in Grafana: the data source, the time range and the panel query, in that order.

Each step rules out one layer: if up returns 1, scraping works, and an empty Grafana panel is a problem with the data source or the query, not the target. A series disappearing after its target is removed from the configuration is normal: the series is marked stale and stops being returned in queries.

A target is DOWN

Cause: Prometheus could not get an HTTP response. The port is not listening, the path differs from metrics_path, the scheme is not https, the TLS handshake failed, or the response did not arrive within scrape_timeout (10s by default). The text of the last error is shown next to the target on the Status → Target health page.

bashon the Prometheus server
# does the target respond to the same request Prometheus makescurl -v http://192.0.2.10:9100/metricspromtool query instant http://localhost:9090 '  scrape_duration_seconds{instance="192.0.2.10:9100"}'

Compare the curl output with the job in prometheus.yml: the address and port come from targets, the path from metrics_path (/metrics by default). If the target is behind a closed port, check the firewall; see the “Linux server hardening” reference, section “Firewall”. A slow target can be fixed by raising scrape_timeout, but do not make the timeout longer than scrape_interval.

A query returns an empty result

Cause: a typo in the metric or label name, a metric that has not been scraped yet (a new target needs at least one interval), or a rate() window narrower than two scrapes. The series may also have gone stale after the target disappeared. The API returns the list of names Prometheus knows:

bashon the Prometheus server
curl http://localhost:9090/api/v1/label/__name__/valuescurl 'http://localhost:9090/api/v1/query?query=up'

A syntax error is visible immediately: the “Table” tab prints text such as parse error: unexpected character with a position in the line. An empty result with no error is not a syntax problem. Check the metric name against the list above, then widen the rate() window to 4 * scrape_interval and look at the query’s time range.

A Grafana panel shows No data

Cause: Grafana could not reach Prometheus, a different data source is selected, or a dashboard variable returned an empty list. The “Save & test” check on a data source confirms only connectivity: it passes even when the metric in the query does not exist. Find out where exactly it is empty:

bashon the Grafana server
# the same query as the panel, bypassing Grafanapromtool query instant http://localhost:9090 'up'sudo journalctl -u grafana-server -n 50

Then, step by step: in the data source settings, check the address; for containers it is the service name, not localhost. Compare the data source’s “Scrape interval” with the actual Prometheus scrape_interval: a mismatch is most visible in rate() queries, which need two samples in the window. Open the query through Inspect → Query to see what $__rate_interval and the variables expanded to. Errors returned by the data source are covered below.

There was an error returned querying the Prometheus API

Cause: Grafana could not connect to Prometheus: the data source address is wrong, Prometheus is not running, or the port is blocked by a firewall. Related messages for the same problem are context deadline exceeded (query timeout) and Failed to parse data source URL (an address without the http:// or https:// scheme).

bashon the Grafana server
# is Prometheus reachable from the Grafana machinecurl http://prometheus:9090/-/healthysudo systemctl status prometheus --no-pager

If the connection works but queries time out, raise “Query timeout” in the data source settings and shorten the panel’s time range. The Grafana server log is in /var/log/grafana/grafana.log, and its verbosity is changed with the [log] section in grafana.ini.

x509: certificate signed by unknown authority

Cause: Grafana could not verify the Prometheus certificate: it is self-signed with no root CA, or the chain is incomplete. In the data source settings, enable “Add self-signed certificate” and add the CA certificate; “Skip TLS verify” is only for testing. A message such as TLS: handshake failure means incompatible TLS versions or ciphers on the two sides.

401 Unauthorized

Cause: Prometheus has authentication enabled in its web configuration, and Grafana is not sending credentials. In the data source settings, enable “Basic authentication” and enter the user and password from the basic_auth_users section of the web configuration file. A 403 Forbidden response means the credentials were accepted, but the user has no permission to read the API.

Metrics are present, but memory and disk keep shrinking

Cause: high cardinality, meaning labels with a large number of values, such as user_id or a full request path. Each label set is a separate time series, with its own cost in memory, CPU and disk. Count the series by metric and label:

bashon the Prometheus server
curl http://localhost:9090/api/v1/status/tsdb | head -40promtool tsdb analyze data/

Instrumentation best practice is to keep label cardinality below 10, with only a handful of metrics on the whole system above 10; above 100 is a signal to change the approach. Move a value such as user_id into logs (see the systemd reference, section “The journal and journalctl”), and keep aggregated breakdowns in labels.

The configuration was not applied

Cause: the file has an error, and the reload via SIGHUP or /-/reload was rejected: the previous configuration keeps running, and the failure is visible only in the log. The /-/reload endpoint is enabled by the --web.enable-lifecycle flag, while SIGHUP always works. Validate before reloading:

bashon the Prometheus server
promtool check config prometheus.ymlkill -HUP "$(pgrep -f prometheus)"sudo journalctl -u prometheus -n 20

The --config.file flag points to the file; the active configuration in expanded form is shown by /api/v1/status/config. Check rule files separately: run promtool check rules before adding them to rule_files.

Minor symptoms

SymptomCauseWhat to do
target DOWN, but curl /metrics worksthe job’s metrics_path is wrongcompare the job’s path and scheme with curl
up = 1, but no metricsthe target responds without metrics, or metric relabeling filtered everything outcheck the target’s scrape_samples_post_metric_relabeling
a series suddenly ends on the graphthe target was removed from the configuration, so the series went stalerestore the target or widen the time range
the panel is empty, but Explore shows dataa different data source is selectedcheck the data source in the query editor
the graph changes with panel widththe panel sets $__interval for the rate() windowset “Min step” or a fixed window
the latest points lag by one intervalthe last scrape has not finished yetthis is normal; check the clocks on both machines

Monitor the monitoring itself: whoever is on call should see an alert on up == 0 and on scraping stopping altogether, absent_over_time(up[5m]). For setting up rules, see the section “Alerting rules and Alertmanager”.

Section sources

the section is written from these pages

Versions and what’s new

This reference covers Prometheus 3.15 and Grafana 13.3. The latest Prometheus release is 3.16.0, from 5 November 2026. A new minor version comes out every 6 weeks, and LTS (long-term support) branches receive fixes for a year.

BranchStatusLatest releaseSupported until
Prometheus 3.16current, receiving releases3.16.0 — 5 November 2026not announced
Prometheus 3.15minor cycle ended3.15.1 — 21 October 2026not announced
Prometheus 3.13 (LTS)fixes for high-CVSS issues3.13.5 — 21 October 202631 July 2027
Prometheus 3.5 (LTS)end of life3.5.5 — 9 July 202631 July 2026
Grafana 13.3current, receiving releases13.3.0 — 27 October 2026not announced
Alertmanager 0.34current, receiving releases0.34.2 — 29 October 2026not announced

Every 6 weeks Prometheus starts a new minor cycle; once it ends, the branch usually receives no more fixes, so fixing a bug means moving to the latest version. Once a year one of the releases is chosen as an LTS branch: for another year it receives only selected fixes rated CVSS 7.0 or higher, plus updates to build tooling and documentation. The support periods of two consecutive LTS branches overlap by at least a month, as the table shows: 3.5 reached end of life in July 2026, when 3.13 was already out.

What changed in 3.15

  • Scraping: a scrape target can respond over a Unix socket, with the socket path given in the static configuration or in service discovery labels.
  • Scraping: targets can respond in the OpenMetrics 2.0 format. It is enabled with the --enable-feature=openmetrics2 flag and is still experimental.
  • Logging: the log level has moved into the configuration. runtime.log_level changes on a configuration reload, without restarting the process.
  • Storage: XOR2 encoding is now stable and is enabled with the storage.tsdb.chunk_encoding.floats: xor2 key (for chunk encodings, see the section “Storage: TSDB and remote write”).
  • Scraping: target responses can be compressed with zstd, enabled with the --enable-feature=zstd-scrape flag.
  • UI: the Targets and Service Discovery pages show the effective configuration of each scrape pool.

The log level is set in the runtime section of the configuration file:

yamlprometheus.yml
runtime:  # log level, changed by reloading the configuration  log_level: info  # GOGC for the Go garbage collector, 75 by default  gogc: 75

What’s new in Grafana 13.3

  • Variables shared across dashboards: define a variable once under “Dashboards → Variables” and make it available to all dashboards in the organisation or in a single folder.
  • Notebooks, a new type of object: dashboard panels, Explore queries and Grafana Assistant findings are assembled into a single editable document that can be shared with a team.
  • Importing an Alertmanager configuration into Grafana Alerting: when moving rules from Prometheus and Mimir, routing and receivers are imported rather than rebuilt.
  • Management of Prometheus, Mimir and Loki rules moves to a separate Prometheus Alerting plugin; alerts managed by Grafana itself stay in the core.
  • Customisable footers in PDF reports.

Deprecated and removed

  • The --log.level flag has been deprecated since 3.15; use runtime.log_level in the configuration.
  • The --enable-feature=xor2-encoding flag is deprecated; use storage.tsdb.chunk_encoding.floats: xor2 in the configuration.
  • The --enable-feature=st-storage flag now enables XOR2 encoding and ST histogram encoding by itself; you no longer need to set their flags separately.
  • Since version 3.9 the --enable-feature=native-histograms flag does nothing: histogram ingestion is enabled with the scrape_native_histograms key in the configuration.
  • To move from 2.x, follow the Prometheus 3.0 migration guide: it lists removed flags, renamed keys and the new Content-Type header requirements for scrape targets.

Security updates

Releases 3.15.1 and 3.13.5, published on 21 October 2026, fixed several vulnerabilities in both branches at once:

What is affectedFixed in
Container images: the emSign ECC Root CA — G3 and Comodo AAA Services root certificates are now untrusted after the compromise of eMudhra’s intermediate keys3.15.1, 3.13.5
Build updated to Go 1.27.3: vulnerabilities in net/http, net/textproto, crypto/tls and html/template3.15.1 (Go 1.26.10 in 3.13.5)
The golang.org/x/net package updated to v0.60.0: HTTP/2 vulnerabilities (GO-2026-6603 … GO-2026-6617)3.15.1, 3.13.5

How to upgrade

Prometheus is upgraded by replacing the binary: stop the process, unpack the new one from the archive in its place (as in the section “Installation and first run”), and leave the configuration and data directory untouched. Before moving to a new minor version, read its release notes: the CHANGE and SECURITY labels show what the upgrade will affect.

bashon the Prometheus server
tar xvfz prometheus-3.16.0.linux-amd64.tar.gzcd prometheus-3.16.0.linux-amd64sudo systemctl stop prometheussudo mv prometheus promtool /usr/local/bin/sudo systemctl start prometheus

Grafana is upgraded with the package manager or by replacing the container; its updates are backward compatible, and dashboards do not change. Before upgrading, back up the /etc/grafana/grafana.ini configuration, the /var/lib/grafana/plugins plugin directory and the database, which by default is an SQLite file; stop Grafana before copying it. The backup lets you return to the previous version. In production, test the upgrade in a staging environment first.

bashon the Grafana server
sudo apt-get updatesudo apt-get upgrade
bashon the Docker host
docker pull grafana/grafana:13.3.0docker stop my-grafana-containerdocker rm my-grafana-containerdocker run -d --name my-grafana-container \  -p 3000:3000 \  -v /var/lib/grafana:/var/lib/grafana \  grafana/grafana:13.3.0

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 3 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

10 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Prometheus and Grafana” topic
13 sections
Another reference · DevOps & cloud

Docker

Verified 31 Oct
All references · 61