Prometheus is an open-source monitoring and alerting system. It scrapes metrics over HTTP from your hosts and services, stores them in its own time-series database (TSDB), evaluates rules against them, and hands firing alerts to Alertmanager, which groups, deduplicates, silences and routes them to mail, chat or a pager.
This guide runs both on Debian 13 “trixie” with the official container images:
- Prometheus 3 (the 3.13 LTS line) and Alertmanager 0.35, pinned, in Docker Compose, running as an unprivileged user with a read-only root filesystem.
- TLS 1.3 and bcrypt basic authentication on both web interfaces, with separate accounts for people, Grafana and Prometheus itself.
- No secrets in config files: every password is read from a
password_file. - Scrape jobs split into files, targets managed with file-based discovery, and the Node Exporter job from my Node Exporter guide.
- Alert and recording rules for Prometheus, Alertmanager and the hosts, including a heartbeat (“dead man’s switch”) so you notice when monitoring itself is down.
- Alertmanager with mail over TLS, grouping, inhibition and a heartbeat receiver.
- nftables, a Grafana data source, tests, capacity planning, backups, upgrades, migrating from the Debian package, troubleshooting and a checklist.
Contents
- Architecture and placeholders
- Install Docker
- User, directories and the compose file
- TLS certificate
- Authentication
- Prometheus configuration
- Scrape jobs and targets
- Recording and alert rules
- Alertmanager
- Start, validate and reload
- Firewall
- Grafana data source
- Testing
- Capacity and retention
- Backups
- Upgrades
- Migrating from the Debian package
- Troubleshooting
- Checklist
1. Architecture and placeholders
โโโโโโโโโโโโโโโโโ prom-01 (Debian 13, Docker) โโโโโโโโโโโโโโโโโ
node exporters โโhttpsโโค Prometheus :9090 (TLS 1.3 + basic auth) โ
(tcp/9100) โ โ alerts (https, basic auth) โ
โ โผ โ
Grafana โโhttpsโโโโโโโโบโ Alertmanager :9093 (TLS 1.3 + basic auth) โโโบ SMTP :587 โ
admins โโhttpsโโโโโโโโบโ โโโบ heartbeat URL โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Both containers use host networking. Docker’s published ports bypass the host firewall; with host networking, nftables (section 11) decides who reaches 9090 and 9093. Alertmanager’s cluster port (9094) is switched off, because there’s only one instance.
| Placeholder | Meaning |
|---|---|
prom-01.example.net / 192.0.2.10 | The Prometheus host. The certificate must contain this name. |
grafana-01.example.net / 192.0.2.11 | Grafana |
198.51.100.0/24 | Admin network (browsers) |
host-01.example.net, host-02.example.net | Nodes running Node Exporter as in my Node Exporter guide |
monitoring-ca.crt | The CA that signs the monitoring certificates (the same CA as in the Node Exporter guide) |
mail.example.net:587 | SMTP server for alert mail |
https://hc.example.net/ping/UUID | Heartbeat URL of a dead man’s switch service (Healthchecks or similar) |
2. Install Docker
Use Docker’s own repository as a deb822 source (as in my Home Assistant guide):
apt install ca-certificates curl apache2-utils jq
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/debian/gpg -o /etc/apt/keyrings/docker.asc
chmod a+r /etc/apt/keyrings/docker.asc
cat > /etc/apt/sources.list.d/docker.sources <<EOF
Types: deb
URIs: https://download.docker.com/linux/debian
Suites: $(. /etc/os-release && echo "$VERSION_CODENAME")
Components: stable
Architectures: $(dpkg --print-architecture)
Signed-By: /etc/apt/keyrings/docker.asc
EOF
apt update
apt install docker-ce docker-ce-cli containerd.io docker-compose-pluginCode language: JavaScript (javascript)
/etc/docker/daemon.json:
{
"ip": "127.0.0.1",
"log-driver": "local",
"log-opts": { "max-size": "10m", "max-file": "5" },
"live-restore": true
}Code language: JSON / JSON with Comments (json)
systemctl restart docker
ipmakes any accidentally published port bind to loopback.localwith a size cap stops container logs from filling the disk.live-restorekeeps Prometheus running whiledockerdis upgraded.
If /etc/nftables.conf contains flush ruleset, remove it: every nftables reload would wipe Docker’s rules. Use per-table files instead (section 11).
apache2-utils provides htpasswd for the bcrypt hashes; jq is for the tests.
3. User, directories and the compose file
The images run as nobody by default. A dedicated system user is better: files can be readable by that user only, and the paths match the Node Exporter guide (root:prometheus, mode 0640).
# Reuse the user if the Debian package created one
id prometheus 2>/dev/null || adduser --system --group --no-create-home --home /nonexistent prometheus
install -d -m 0755 /etc/prometheus /etc/prometheus/rules /etc/prometheus/scrape.d /etc/prometheus/targets
install -d -m 0750 -g prometheus /etc/prometheus/ssl /etc/prometheus/secrets
install -d -m 0755 /etc/alertmanager
install -d -m 0750 -g prometheus /etc/alertmanager/secrets
install -d -m 0750 -o prometheus -g prometheus /srv/prometheus/data /srv/alertmanager/data
install -d -m 0750 /opt/compose/monitoringCode language: PHP (php)
The host’s /etc/prometheus is mounted read-only at the same path inside the container, so every path in this guide is the same on the host and in the container.
/opt/compose/monitoring/.env:
cat > /opt/compose/monitoring/.env <<EOF
PROM_TAG=v3.13.5
AM_TAG=v0.35.0
PROM_UID=$(id -u prometheus)
PROM_GID=$(id -g prometheus)
EOF
chmod 600 /opt/compose/monitoring/.envCode language: JavaScript (javascript)
v3.13.5 is the current release of the 3.13 LTS line (supported until July 2027). Use the newest 3.x release instead if you want features sooner and are happy to upgrade monthly.
/opt/compose/monitoring/compose.yaml:
name: monitoring
x-hardening: &hardening
user: "${PROM_UID}:${PROM_GID}"
network_mode: host
read_only: true
cap_drop: [ALL]
security_opt:
- no-new-privileges:true
tmpfs:
- /tmp
restart: unless-stopped
services:
prometheus:
<<: *hardening
container_name: prometheus
image: quay.io/prometheus/prometheus:${PROM_TAG}
command:
- --config.file=/etc/prometheus/prometheus.yml
- --web.config.file=/etc/prometheus/web.yml
- --storage.tsdb.path=/prometheus
- --web.listen-address=:9090
- --web.external-url=https://prom-01.example.net:9090/
volumes:
- /etc/prometheus:/etc/prometheus:ro
- /srv/prometheus/data:/prometheus
mem_limit: 4g # Prometheus sets GOMEMLIMIT from this automatically
stop_grace_period: 2m # time to close the TSDB cleanly
alertmanager:
<<: *hardening
container_name: alertmanager
image: quay.io/prometheus/alertmanager:${AM_TAG}
command:
- --config.file=/etc/alertmanager/alertmanager.yml
- --web.config.file=/etc/alertmanager/web.yml
- --storage.path=/alertmanager
- --web.listen-address=:9093
- --web.external-url=https://prom-01.example.net:9093/
- --cluster.listen-address= # empty: no HA gossip on 9094
volumes:
- /etc/alertmanager:/etc/alertmanager:ro
- /etc/prometheus/ssl:/etc/alertmanager/ssl:ro
- /srv/alertmanager/data:/alertmanager
mem_limit: 256mCode language: PHP (php)
Notes:
- The images come from Quay (
quay.io/prometheus/...), the same images asprom/...on Docker Hub, without Docker Hub’s pull rate limits. - What’s not enabled, on purpose:
--web.enable-lifecycle(lets anyone with a login stop Prometheus over HTTP; reload with SIGHUP instead) and--web.enable-admin-api(lets anyone with a login delete data; see section 15). - Hardening: no capabilities, no privilege escalation, a read-only image filesystem. Prometheus and Alertmanager only write to their data volumes.
- Retention isn’t a flag here. In Prometheus 3 the retention flags are deprecated in favour of the config file (section 6).
4. TLS certificate
Issue one certificate for prom-01.example.net from your monitoring CA (Appendix A of the Node Exporter guide has a minimal OpenSSL CA). Prometheus and Alertmanager share it. The SAN must contain the name that Grafana, the browsers and Prometheus itself use.
install -m 0644 monitoring-ca.crt /etc/prometheus/ssl/monitoring-ca.crt
install -m 0644 prom-01.crt /etc/prometheus/ssl/prometheus.crt
install -m 0640 -g prometheus prom-01.key /etc/prometheus/ssl/prometheus.key
openssl x509 -in /etc/prometheus/ssl/prometheus.crt -noout -subject -ext subjectAltName -enddate
openssl verify -CAfile /etc/prometheus/ssl/monitoring-ca.crt /etc/prometheus/ssl/prometheus.crt
If your certificate needs an intermediate, append it to prometheus.crt (server certificate first).
Both services re-read their web config and certificate files on every request, so a renewed certificate is used immediately, without a restart.
5. Authentication
Prometheus and Alertmanager store only bcrypt hashes (in web.yml). Clients that log in automatically (Prometheus itself, Grafana) read the plaintext password from a file.
| Account | Used by | Where the plaintext lives |
|---|---|---|
admin | People, in the browser | Your password manager |
grafana | Grafana’s data source | Grafana’s data source settings |
prometheus | Prometheus scraping itself and Alertmanager, and sending alerts | /etc/prometheus/secrets/self.pass |
Generate the passwords and hashes:
cd /etc/prometheus/secrets
umask 027
for u in admin grafana self; do openssl rand -base64 32 | tr -d '\n' > $u.pass; done
chgrp prometheus *.pass
for u in admin grafana self; do
printf '%s: ' "$u"; htpasswd -niBC 12 "" < $u.pass | tr -d ':\n'; echo
doneCode language: PHP (php)
Copy admin.pass and grafana.pass into your password manager, then delete them from the server; only self.pass needs to stay:
shred -u /etc/prometheus/secrets/admin.pass /etc/prometheus/secrets/grafana.pass
/etc/prometheus/web.yml:
tls_server_config:
cert_file: /etc/prometheus/ssl/prometheus.crt
key_file: /etc/prometheus/ssl/prometheus.key
min_version: TLS13
http_server_config:
http2: true
headers:
Strict-Transport-Security: max-age=31536000
X-Frame-Options: deny
X-Content-Type-Options: nosniff
basic_auth_users:
admin: "$2y$12$REPLACE.WITH.THE.ADMIN.HASH"
grafana: "$2y$12$REPLACE.WITH.THE.GRAFANA.HASH"
prometheus: "$2y$12$REPLACE.WITH.THE.SELF.HASH"Code language: JavaScript (javascript)
/etc/alertmanager/web.yml is the same, but with the certificate paths under /etc/alertmanager/ssl/ (the read-only mount from the compose file), and without the grafana user unless you use Grafana’s Alertmanager data source:
tls_server_config:
cert_file: /etc/alertmanager/ssl/prometheus.crt
key_file: /etc/alertmanager/ssl/prometheus.key
min_version: TLS13
http_server_config:
http2: true
headers:
Strict-Transport-Security: max-age=31536000
X-Frame-Options: deny
X-Content-Type-Options: nosniff
basic_auth_users:
admin: "$2y$12$REPLACE.WITH.THE.ADMIN.HASH"
prometheus: "$2y$12$REPLACE.WITH.THE.SELF.HASH"Code language: JavaScript (javascript)
chgrp prometheus /etc/prometheus/web.yml /etc/alertmanager/web.yml
chmod 640 /etc/prometheus/web.yml /etc/alertmanager/web.yml
Check both files (promtool is in the Prometheus image):
P="docker run --rm --network none --entrypoint promtool -v /etc/prometheus:/etc/prometheus:ro -v /etc/alertmanager:/etc/alertmanager:ro quay.io/prometheus/prometheus:v3.13.5"
$P check web-config /etc/prometheus/web.yml
$P check web-config /etc/alertmanager/web.ymlCode language: PHP (php)
Limits of basic auth: every account sees all metrics, and there are no roles. If you need single sign-on or per-user access, put a reverse proxy such as oauth2-proxy in front and keep this config for the machine accounts. Also note that
--web.config.fileis still marked experimental in the Prometheus docs, even though it has been stable in practice for years.
6. Prometheus configuration
/etc/prometheus/prometheus.yml:
global:
scrape_interval: 15s
scrape_timeout: 10s
evaluation_interval: 15s
external_labels:
site: dc1 # identifies this Prometheus in alerts and federation
storage:
tsdb:
retention:
time: 60d
size: 40GB # whichever limit is reached first wins
alerting:
alertmanagers:
- scheme: https
api_version: v2
tls_config:
ca_file: /etc/prometheus/ssl/monitoring-ca.crt
min_version: TLS13
basic_auth:
username: prometheus
password_file: /etc/prometheus/secrets/self.pass
static_configs:
- targets: ['prom-01.example.net:9093']
rule_files:
- /etc/prometheus/rules/*.yml
scrape_config_files:
- /etc/prometheus/scrape.d/*.ymlCode language: PHP (php)
- Retention: keep 60 days, but never use more than 40 GB. Size the volume with headroom (section 14). The size limit counts blocks and the WAL, so keep it at roughly 80% of the space you give Prometheus.
scrape_config_filesloads every job fromscrape.d/, so each job lives in its own file.external_labelsare added to every alert, which matters as soon as you run a second Prometheus.
chgrp prometheus /etc/prometheus/prometheus.yml && chmod 640 /etc/prometheus/prometheus.yml
7. Scrape jobs and targets
All jobs use the dedicated CA, TLS 1.3 and a password_file. /etc/prometheus/scrape.d/prometheus.yml:
scrape_configs:
- job_name: prometheus
scheme: https
tls_config:
ca_file: /etc/prometheus/ssl/monitoring-ca.crt
min_version: TLS13
basic_auth:
username: prometheus
password_file: /etc/prometheus/secrets/self.pass
static_configs:
- targets: ['prom-01.example.net:9090']
- job_name: alertmanager
scheme: https
tls_config:
ca_file: /etc/prometheus/ssl/monitoring-ca.crt
min_version: TLS13
basic_auth:
username: prometheus
password_file: /etc/prometheus/secrets/self.pass
static_configs:
- targets: ['prom-01.example.net:9093']Code language: JavaScript (javascript)
/etc/prometheus/scrape.d/node.yml, the Node Exporter job from my Node Exporter guide, now with file-based discovery:
scrape_configs:
- job_name: node
scheme: https
tls_config:
ca_file: /etc/prometheus/ssl/monitoring-ca.crt
min_version: TLS13
basic_auth:
username: prometheus
password_file: /etc/prometheus/secrets/node-exporter.pass
file_sd_configs:
- files: ['/etc/prometheus/targets/node*.yml']
relabel_configs:
# instance="host-01.example.net" instead of "host-01.example.net:9100"
- source_labels: [__address__]
regex: '(.+):\d+'
target_label: instance
replacement: '$1'Code language: PHP (php)
node-exporter.pass is the password created in section 5.1 of the Node Exporter guide. Put it in /etc/prometheus/secrets/ with mode 0640 root:prometheus.
/etc/prometheus/targets/node.yml:
- targets:
- host-01.example.net:9100
- host-02.example.net:9100
- prom-01.example.net:9100 # monitor the Prometheus host too
labels:
env: prodCode language: CSS (css)
Prometheus re-reads target files when they change, without a reload. Adding a host is one line. Since the container mounts /etc/prometheus read-only, you edit the files on the host as root, as usual.
Every target name must match the certificate on that target. Prometheus 3 also fails scrapes when a target sends no or an unknown
Content-Type. Current exporters are fine; for an old or odd one, setfallback_scrape_protocol: PrometheusText0.0.4on its job.
8. Recording and alert rules
8.1 Recording rules
Recording rules precompute expensive queries so dashboards and alerts stay fast. /etc/prometheus/rules/recording.yml:
groups:
- name: node-recording
interval: 30s
rules:
- record: instance:node_cpu_utilisation:rate5m
expr: 1 - avg by (instance) (rate(node_cpu_seconds_total{job="node",mode="idle"}[5m]))
- record: instance:node_memory_utilisation:ratio
expr: 1 - node_memory_MemAvailable_bytes{job="node"} / node_memory_MemTotal_bytes{job="node"}Code language: JavaScript (javascript)
8.2 Prometheus and Alertmanager alerts
/etc/prometheus/rules/monitoring.yml:
groups:
- name: meta
rules:
# Always firing. Alertmanager sends it to the heartbeat service, which
# alerts YOU when the pings stop (Prometheus, Alertmanager or mail broken).
- alert: Watchdog
expr: vector(1)
labels:
severity: none
annotations:
summary: "Heartbeat: the alerting pipeline works"
- alert: TargetDown
expr: up == 0
for: 5m
labels:
severity: critical
annotations:
summary: "{{ $labels.job }} target {{ $labels.instance }} is down"
description: "Scrapes have failed for 5 minutes (host down, firewall, TLS or auth problem). See Status โ Target health."
- name: prometheus
rules:
- alert: PrometheusConfigReloadFailed
expr: prometheus_config_last_reload_successful == 0
for: 5m
labels:
severity: warning
annotations:
summary: "Prometheus config reload failed; it is still running the old config"
- alert: PrometheusRuleEvaluationFailures
expr: increase(prometheus_rule_evaluation_failures_total[5m]) > 0
for: 15m
labels:
severity: warning
annotations:
summary: "Rule group {{ $labels.rule_group }} fails to evaluate"
- alert: PrometheusNotConnectedToAlertmanager
expr: prometheus_notifications_alertmanagers_discovered < 1
for: 5m
labels:
severity: critical
annotations:
summary: "Prometheus has no Alertmanager to send alerts to"
- alert: PrometheusNotificationsFailing
expr: rate(prometheus_notifications_errors_total[5m]) > 0
for: 10m
labels:
severity: critical
annotations:
summary: "Prometheus fails to deliver alerts to {{ $labels.alertmanager }}"
- alert: PrometheusTSDBCompactionsFailing
expr: increase(prometheus_tsdb_compactions_failed_total[3h]) > 0
labels:
severity: warning
annotations:
summary: "TSDB compactions are failing (disk full or corrupted block?)"
- alert: PrometheusTSDBReloadsFailing
expr: increase(prometheus_tsdb_reloads_failures_total[3h]) > 0
labels:
severity: warning
annotations:
summary: "TSDB block reloads are failing"
- alert: PrometheusRuleGroupTooSlow
expr: prometheus_rule_group_last_duration_seconds > prometheus_rule_group_interval_seconds
for: 15m
labels:
severity: warning
annotations:
summary: "Rule group {{ $labels.rule_group }} takes longer than its interval"
- name: alertmanager
rules:
- alert: AlertmanagerConfigReloadFailed
expr: alertmanager_config_last_reload_successful == 0
for: 5m
labels:
severity: warning
annotations:
summary: "Alertmanager config reload failed; it is still running the old config"
- alert: AlertmanagerNotificationsFailing
expr: rate(alertmanager_notifications_failed_total[5m]) > 0
for: 10m
labels:
severity: critical
annotations:
summary: "Alertmanager fails to send via {{ $labels.integration }}"Code language: PHP (php)
8.3 Host alerts
Copy node.yml from section 11 of the Node Exporter guide to /etc/prometheus/rules/node.yml. It covers disk space, disk fill prediction, memory, load, time sync, failed systemd units, reboots and textfile errors. Drop its own target-down alert if it has one, since TargetDown above covers every job.
chgrp -R prometheus /etc/prometheus/rules /etc/prometheus/scrape.d /etc/prometheus/targets
chmod 640 /etc/prometheus/rules/*.yml /etc/prometheus/scrape.d/*.yml /etc/prometheus/targets/*.yml
Rules can be unit-tested with promtool test rules. That’s worth it for the alerts that wake people up.
9. Alertmanager
Store the SMTP password and the heartbeat URL as files:
umask 027
printf '%s' 'SMTP-PASSWORD' > /etc/alertmanager/secrets/smtp.pass
printf '%s' 'https://hc.example.net/ping/UUID' > /etc/alertmanager/secrets/heartbeat.url
chgrp prometheus /etc/alertmanager/secrets/*Code language: JavaScript (javascript)
(Typing the password on the command line puts it in your shell history. Use read -rs P && printf '%s' "$P" > ... if that matters to you.)
/etc/alertmanager/alertmanager.yml:
global:
resolve_timeout: 5m
smtp_smarthost: mail.example.net:587
smtp_from: alertmanager@example.net
smtp_auth_username: alertmanager@example.net
smtp_auth_password_file: /etc/alertmanager/secrets/smtp.pass
smtp_require_tls: true
smtp_hello: prom-01.example.net
route:
receiver: ops-mail
group_by: [alertname, job]
group_wait: 30s
group_interval: 5m
repeat_interval: 4h
routes:
- matchers: ['alertname = "Watchdog"']
receiver: heartbeat
group_wait: 0s
group_interval: 1m
repeat_interval: 1m
- matchers: ['severity = "critical"']
receiver: ops-mail
repeat_interval: 1h
inhibit_rules:
# A critical alert silences the matching warning
- source_matchers: ['severity = "critical"']
target_matchers: ['severity = "warning"']
equal: [alertname, instance]
# A host that is down doesn't also need its other alerts
- source_matchers: ['alertname = "TargetDown"']
target_matchers: ['alertname != "TargetDown"']
equal: [instance]
receivers:
- name: ops-mail
email_configs:
- to: ops@example.net
send_resolved: true
- name: heartbeat
webhook_configs:
- url_file: /etc/alertmanager/secrets/heartbeat.url
send_resolved: falseCode language: PHP (php)
How it fits together:
- Grouping sends one mail per alert name and job instead of one per host when, for example, a network outage takes ten hosts down.
- The heartbeat receives the always-firing
Watchdogalert every minute. The heartbeat service (Healthchecks, self-hosted or not, on a different machine) alerts you if the pings stop. That’s the only way to learn that Prometheus, Alertmanager or the mail path is broken. - Inhibition keeps a host outage from becoming twenty mails.
smtp_require_tlsrefuses to send if STARTTLS isn’t offered. If your mail server uses a private CA, addsmtp_tls_config: { ca_file: ... }.
chgrp prometheus /etc/alertmanager/alertmanager.yml && chmod 640 /etc/alertmanager/alertmanager.yml
docker run --rm --network none --entrypoint amtool -v /etc/alertmanager:/etc/alertmanager:ro \
quay.io/prometheus/alertmanager:v0.35.0 check-config /etc/alertmanager/alertmanager.ymlCode language: JavaScript (javascript)
10. Start, validate and reload
Check everything before the first start:
P="docker run --rm --network none --entrypoint promtool -v /etc/prometheus:/etc/prometheus:ro quay.io/prometheus/prometheus:v3.13.5"
$P check config /etc/prometheus/prometheus.yml
$P check rules /etc/prometheus/rules/*.ymlCode language: PHP (php)
check config also loads the rule files and checks that every ca_file and password_file exists. If it fails, don’t start or reload.
cd /opt/compose/monitoring
docker compose up -d
docker compose ps
docker compose logs prometheus | grep -Ei 'tls|listening|completed loading|error'
docker compose logs alertmanager | grep -Ei 'tls|listening|completed loading|error'Code language: JavaScript (javascript)
Look for TLS is enabled, Listening on, Completed loading of configuration file and no errors.
Reloading after a change (config, rules or scrape files): validate, then send SIGHUP. Prometheus keeps running the old config if the new one is invalid.
$P check config /etc/prometheus/prometheus.yml && docker compose kill -s SIGHUP prometheus
docker compose logs --since 1m prometheus | grep -i 'loading'Code language: PHP (php)
For Alertmanager, run amtool check-config first, then docker compose kill -s SIGHUP alertmanager. web.yml, certificates and target files need no reload.
Add a helper so validation is never skipped:
cat > /usr/local/sbin/prom-reload <<'EOF'
#!/bin/sh
set -e
TAG=$(sed -n 's/^PROM_TAG=//p' /opt/compose/monitoring/.env)
docker run --rm --network none --entrypoint promtool -v /etc/prometheus:/etc/prometheus:ro \
quay.io/prometheus/prometheus:$TAG check config /etc/prometheus/prometheus.yml
docker compose -f /opt/compose/monitoring/compose.yaml kill -s SIGHUP prometheus
echo "Reloaded. Check: docker compose -f /opt/compose/monitoring/compose.yaml logs --since 1m prometheus"
EOF
chmod 750 /usr/local/sbin/prom-reloadCode language: PHP (php)
11. Firewall
/etc/nftables.d/prometheus.nft:
destroy table inet prometheus
table inet prometheus {
set admin_v4 { type ipv4_addr; flags interval; elements = { 198.51.100.0/24 } }
set grafana_v4 { type ipv4_addr; elements = { 192.0.2.11 } }
chain input {
type filter hook input priority filter - 10; policy accept;
iif "lo" accept
# Prometheus UI/API: admins and Grafana
tcp dport 9090 ip saddr { @admin_v4, @grafana_v4 } accept
tcp dport 9090 counter drop
# Alertmanager UI/API: admins only (Prometheus connects locally)
tcp dport 9093 ip saddr @admin_v4 accept
tcp dport 9093 counter drop
# Alertmanager cluster port: disabled, and never reachable
tcp dport 9094 counter drop
udp dport 9094 counter drop
}
}Code language: PHP (php)
nft -c -f /etc/nftables.d/prometheus.nft && nft -f /etc/nftables.d/prometheus.nft
Prometheus reaching its own FQDN goes over the loopback interface, so iif "lo" covers the self-scrape and alert delivery. Outbound (scrapes to port 9100 on the nodes, SMTP, the heartbeat) needs no rule here; the nodes’ own firewalls allow only 192.0.2.10 (Node Exporter guide, section 2).
12. Grafana data source
In Grafana, Connections โ Data sources โ Add โ Prometheus:
- URL:
https://prom-01.example.net:9090 - Authentication: Basic authentication, user
grafanaand its password. - TLS settings: Add self-signed certificate (the CA option) and paste
monitoring-ca.crt. Leave Skip TLS verify off. - Prometheus type: Prometheus, with the version you run (it enables the right query features).
- Scrape interval: 15s, the same as the global interval, so
$__rate_intervalis right.
Save & test should say the data source works. If Grafana says x509: certificate signed by unknown authority, the CA wasn’t pasted, or Grafana uses a different name than the certificate’s SAN.
13. Testing
Run these from an admin workstation that has monitoring-ca.crt and the passwords.
CA=monitoring-ca.crt
U=https://prom-01.example.net:9090
read -rs PW # the admin password
# Without credentials: 401
curl -sS -o /dev/null -w '%{http_code}\n' --cacert $CA $U/api/v1/status/buildinfo
# Plain HTTP: refused (the server only speaks TLS)
curl -sS -m 5 http://prom-01.example.net:9090/ ; echo "exit=$?"
# TLS 1.2: refused (min_version TLS13)
openssl s_client -connect prom-01.example.net:9090 -tls1_2 </dev/null 2>&1 | grep -iE 'alert|error' | head -n 2
# With credentials: version, readiness, targets
curl -sS --cacert $CA -u admin:"$PW" $U/api/v1/status/buildinfo | jq -r .data.version
curl -sS --cacert $CA -u admin:"$PW" $U/-/ready
curl -sS --cacert $CA -u admin:"$PW" $U/api/v1/targets?state=active \
| jq -r '.data.activeTargets[] | [.labels.job, .labels.instance, .health, .lastError] | @tsv'Code language: PHP (php)
Every target should show up with an empty error. Then check the rules and Alertmanager:
curl -sS --cacert $CA -u admin:"$PW" $U/api/v1/rules | jq -r '.data.groups[] | [.name, (.rules|length)] | @tsv'
curl -sS --cacert $CA -u admin:"$PW" $U/api/v1/alertmanagers | jq -r '.data.activeAlertmanagers[].url'Code language: PHP (php)
End-to-end alert test. Send a fake alert straight to Alertmanager; a mail should arrive within a minute, and a resolved mail after five:
curl -sS --cacert $CA -u admin:"$PW" -H 'Content-Type: application/json' \
-d '[{"labels":{"alertname":"TestAlert","severity":"warning","instance":"test"},"annotations":{"summary":"Test alert from curl"}}]' \
https://prom-01.example.net:9093/api/v2/alertsCode language: PHP (php)
Real failure test. Stop Node Exporter on one host for six minutes (systemctl stop prometheus-node-exporter). TargetDown must arrive by mail, and the host’s other alerts must be inhibited. Start it again and wait for the resolved mail.
Heartbeat test. Stop Alertmanager (docker compose stop alertmanager). The heartbeat service must alert you after its grace period. Start it again.
Firewall test. From a machine outside the admin network, nc -zvw3 prom-01.example.net 9090 must time out.
In the web UI, Status โ Target health shows the same as the targets query:

14. Capacity and retention
Prometheus needs roughly 1 to 2 bytes per sample on disk. Measure your ingestion rate after a day:
rate(prometheus_tsdb_head_samples_appended_total[1h])Code language: CSS (css)
Disk needed โ samples per second ร retention in seconds ร 2 bytes. For example, 20,000 samples per second for 60 days: 20,000 ร 5,184,000 ร 2 โ 207 GB. Set the volume size, then the size: retention at about 80% of it.
Other things to watch (in the UI, or as Grafana panels):
| Query | Tells you |
|---|---|
prometheus_tsdb_head_series | Active series. Sudden jumps mean a label explosion (a target putting IDs or URLs in labels). |
topk(10, count by (__name__) ({__name__=~".+"})) | Which metrics have the most series (expensive: run it rarely) |
scrape_duration_seconds | Slow targets, close to scrape_timeout |
prometheus_tsdb_storage_blocks_bytes | Space used by blocks |
process_resident_memory_bytes{job="prometheus"} | Memory, against the 4 GB mem_limit |
Memory grows with the number of active series, roughly a few KB per series. If Prometheus approaches mem_limit, raise the limit or drop unneeded metrics with metric_relabel_configs on the job that produces them.
15. Backups
What must be backed up (small, and enough to rebuild everything):
| Path | Contents |
|---|---|
/etc/prometheus/ | Config, rules, scrape jobs, targets, web config, certificates, self.pass, node-exporter.pass |
/etc/alertmanager/ | Config, web config, SMTP password, heartbeat URL |
/opt/compose/monitoring/ | Compose file and .env with the pinned versions |
/srv/alertmanager/data/ | Silences and notification state (small) |
/etc/nftables.d/prometheus.nft, /etc/docker/daemon.json, /usr/local/sbin/prom-reload | Host config |
The metrics themselves (/srv/prometheus/data) are often treated as expendable: after a loss you lose history, not monitoring. If you need the history:
- A filesystem snapshot (LVM, ZFS or the hypervisor) of the data volume is consistent enough. Prometheus recovers from the WAL like after a crash.
- Or the TSDB snapshot API, which needs
--web.enable-admin-api. That flag also enables the endpoints that delete series, for every account inweb.yml. If you use it, enable it only while taking the snapshot, or put a proxy in front that allows onlyPOST /api/v1/admin/tsdb/snapshotfrom the backup host.
Restore test, once: a fresh Debian 13 VM, section 2, restore the paths above, docker compose up -d, and check the targets come up.
16. Upgrades
- Stay on the LTS line (3.13.x) for bug and security fixes with no new features. Move to the next LTS when it’s released, after reading its migration notes.
- Read the release notes for Prometheus and Alertmanager.
- Change the tag in
.env, check the config with the new image’spromtool, then restart:
cd /opt/compose/monitoring
sed -i 's/^PROM_TAG=.*/PROM_TAG=v3.13.6/' .env # example
docker run --rm --network none --entrypoint promtool -v /etc/prometheus:/etc/prometheus:ro \
quay.io/prometheus/prometheus:v3.13.6 check config /etc/prometheus/prometheus.yml
docker compose pull prometheus
docker compose up -d prometheus
docker compose logs -f prometheus # WAL replay, then "Server is ready to receive web requests"Code language: PHP (php)
- Restarting Prometheus causes a gap while the WAL is replayed (seconds to minutes, depending on series). Alerts with a
for:duration restart their timer.
To be told about new versions, use Diun as in my Home Assistant guide, or subscribe to the GitHub release feeds of prometheus/prometheus and prometheus/alertmanager.
17. Migrating from the Debian package
The Debian package ran Prometheus 2.x as the prometheus user with data in /var/lib/prometheus/ (or /var/lib/prometheus/data if you set that path). Prometheus 3 reads 2.x data.
- Install Docker (section 2) and write the new config (sections 3 to 9), keeping the
prometheususer that the package created. Check it withpromtoolfrom the new image. - Stop the package and copy the data:
systemctl disable --now prometheus prometheus-alertmanager 2>/dev/null
rsync -aH /var/lib/prometheus/data/ /srv/prometheus/data/
chown -R prometheus:prometheus /srv/prometheus/dataCode language: JavaScript (javascript)
- Start the containers (section 10) and check that old data shows up in a graph covering the last few days.
- Remove the packages once you’re happy. Use
remove, notpurge, until you’ve confirmed nothing else needs the old config:apt remove prometheus prometheus-alertmanager. Don’t removeprometheus-node-exporter; this host’s own exporter stays a package.
Things that behave differently in Prometheus 3:
- Regex
.in PromQL and relabel rules now also matches newlines. - Range selectors are left-open: a sample exactly at the start of the range is no longer included.
leandquantilelabels are normalised (le="1"becomesle="1.0"). Queries and dashboards that matchle="1"literally need updating.- Scrapes without a valid
Content-Typefail unlessfallback_scrape_protocolis set. holt_wintersis nowdouble_exponential_smoothing, behind a feature flag.- Feature flags that became defaults were removed; Prometheus refuses to start with flags it doesn’t know.
- Downgrading is only possible to 2.55.
18. Troubleshooting
| Symptom | Cause and fix |
|---|---|
Container restarts, log says permission denied on /prometheus | Data directory not owned by the prometheus user, or PROM_UID in .env wrong. ls -ln /srv/prometheus and id prometheus. |
open /etc/prometheus/secrets/...: permission denied | Files must be group prometheus, mode 0640, and the directory 0750 with group prometheus. |
Target error x509: certificate is valid for ..., not ... | The target name in targets/*.yml doesn’t match the certificate’s SAN. |
Target error x509: certificate signed by unknown authority | Wrong ca_file, or the target’s certificate is missing its intermediate. |
Target error server returned HTTP status 401 | Wrong password file for that job, or the hash on the target doesn’t match. |
Target error about Content-Type | Prometheus 3 strictness; set fallback_scrape_protocol on the job. |
PrometheusNotConnectedToAlertmanager | Alertmanager down, wrong credentials, or the certificate doesn’t contain prom-01.example.net. curl Alertmanager with the prometheus account. |
| Alerts fire in Prometheus but no mail arrives | docker compose logs alertmanager | grep -i notify; check SMTP credentials, STARTTLS and the from address the mail server allows. |
| Reload doesn’t take effect | The new config is invalid. Prometheus logs an error and keeps the old config; PrometheusConfigReloadFailed fires after 5 minutes. |
| Containers lose network after reloading nftables | flush ruleset in /etc/nftables.conf; remove it and restart Docker. |
Prometheus is killed (OOMKilled in docker inspect) | Too many series for mem_limit. Find the culprit (section 14), drop metrics or raise the limit. |
Start fails with read-only file system | A component wants to write outside its volume. Check the log for the path and add a tmpfs for it, rather than removing read_only. |
19. Checklist
- โ Docker from Docker’s deb822 repository;
daemon.jsonwithip: 127.0.0.1and capped logs; noflush ruleset - โ Images pinned in
.env(Prometheus LTS line, Alertmanager), pulled from Quay - โ Containers run as the
prometheususer, read-only, no capabilities, no privilege escalation - โ
--web.enable-lifecycleand--web.enable-admin-apioff - โ Certificate for
prom-01.example.netfrom the monitoring CA; key0640 root:prometheus - โ
web.ymlfor both services: TLS 1.3, security headers, bcrypt usersadmin,grafana,prometheus - โ Only
self.passandnode-exporter.passon the server; other passwords in the password manager - โ Retention: time and size set; volume sized from the ingestion rate
- โ Scrape jobs in
scrape.d/, targets intargets/, every target name matching its certificate - โ
promtool check configandcheck rulespass; reloads go throughprom-reload - โ Rules:
Watchdog,TargetDown, Prometheus and Alertmanager health, node rules - โ Alertmanager: mail over TLS, grouping, inhibition, heartbeat to a service on another machine
- โ Test alert, a real target-down and the heartbeat all verified
- โ nftables: 9090 from admins and Grafana only, 9093 from admins only, 9094 closed
- โ Grafana data source with basic auth and the CA, TLS verification on
- โ Config backups in place; restore tested once