Prometheus Monitoring: Complete Observability Guide
· Pavan Y N · monitoring, observability, kubernetes, devops
Prometheus is an open-source monitoring and alerting toolkit built around a multi-dimensional time series data model, a pull-based collection model, and a query language called PromQL. EduGeek explains how the pieces fit together, how to run Prometheus 3.x on Docker and Kubernetes, which PromQL patterns are safe to copy, and how to wire up alerting without the configuration that older tutorials still recommend.
As of October 2026 the newest Prometheus minor release is 3.15, and 3.13 is the long-term support (LTS) release, supported until July 31, 2027. A new minor release starts every six weeks, so pin an exact image tag instead of latest and plan upgrades around the release cycle.
# What is Prometheus?
Prometheus scrapes metrics from HTTP endpoints at a fixed interval, stores them in a local time series database (TSDB), evaluates rules against the stored data, and sends firing alerts to a separate component called Alertmanager.
## Key features
- →Multi-dimensional data model: every time series is identified by a metric name plus key/value labels.
- →PromQL: a query language for selecting, aggregating, and transforming series.
- →Pull-based collection: Prometheus scrapes targets over HTTP. Short-lived batch jobs can push to a Pushgateway, and Prometheus can also receive OpenTelemetry Protocol (OTLP) metrics when started with
--web.enable-otlp-receiver. - →Service discovery: targets come from static lists or from systems such as Kubernetes, Consul, and cloud provider APIs.
- →Alerting: alert rules live in Prometheus, while grouping, routing, silencing, and notification live in Alertmanager.
- →Visualization: a built-in expression browser for ad hoc queries, with Grafana for dashboards.
## Metric types
| Type | Behavior | Typical use |
|---|---|---|
| Counter | Only goes up (resets to zero on restart) | Requests, errors, bytes sent |
| Gauge | Goes up and down | Memory in use, queue length |
| Histogram | Counts observations in buckets, plus a sum and a count | Request latency, response size |
| Summary | Client-side quantiles, plus a sum and a count | Latency when aggregation is not needed |
## Architecture
Service discovery
|
v
+---------------------------------------------+
| Prometheus server |
| Scrape --> TSDB --> Rule evaluation |
| \--> HTTP API / PromQL |
+---------------------------------------------+
^ pull /metrics | alerts ^ queries
| v |
Targets / exporters Alertmanager Grafana
|
Slack, PagerDuty, email, webhooks
Local storage is not clustered or replicated, so a single Prometheus server behaves like a single-node database. The data directory must be on a local POSIX-compliant filesystem, and network filesystems such as NFS or Amazon EFS are not supported. See the storage documentation.
## What changed in Prometheus 3
Prometheus 3.0 shipped breaking changes that affect older tutorials, dashboards, and alerts. The most relevant ones, from the migration guide:
| Area | Change in 3.x |
|---|---|
| Metric and label names | UTF-8 names are accepted by default. Legacy-only validation is available with metric_name_validation_scheme: legacy. |
le and quantile labels | Values are normalized to float form on ingest, so le="1" becomes le="1.0". Queries that match whole-number values must be updated. |
| Range selectors | Ranges are left-open and right-closed, so a 5m range now returns five evenly spaced samples instead of sometimes six. |
| Regex matchers | . now matches newline characters. |
holt_winters | Renamed double_exponential_smoothing and moved behind --enable-feature=promql-experimental-functions. |
| Scrape content type | A missing or unrecognized Content-Type now fails the scrape. Use fallback_scrape_protocol for misbehaving targets. |
| Alertmanager API | The v1 API is removed. Prometheus 3 requires Alertmanager 0.16 or later and api_version: v2. |
| Histogram settings | scrape_classic_histograms is now always_scrape_classic_histograms. Scraping native histograms requires scrape_native_histograms. |
| Logging | The log format changed because Prometheus moved to Go's log/slog. |
UTF-8 names that are not legal in the classic syntax are quoted inside the braces, for example {"http.server.request.duration", "service.name"="checkout"}.
# Installation and setup
## Docker Compose
Prometheus reads rule files and a configuration file from /etc/prometheus and stores data in /prometheus inside the official image. The image's default flags are replaced, not extended, when a command is given, so the config and data paths are repeated below.
prometheus.yml:
global:
scrape_interval: 15s # the built-in default is 1m
evaluation_interval: 15s
external_labels:
cluster: production
region: us-east-1
alerting:
alertmanagers:
- static_configs:
- targets: ['alertmanager:9093']
rule_files:
- /etc/prometheus/rules/*.yml
scrape_configs:
- job_name: prometheus
static_configs:
- targets: ['localhost:9090']
- job_name: node
static_configs:
- targets: ['host.docker.internal:9100']
- job_name: application
metrics_path: /metrics
scrape_interval: 10s
static_configs:
- targets: ['app:3000']
compose.yaml:
services:
prometheus:
image: prom/prometheus:v3.15.0
ports:
- "9090:9090"
command:
- --config.file=/etc/prometheus/prometheus.yml
- --storage.tsdb.path=/prometheus
- --storage.tsdb.retention.time=30d
- --web.enable-lifecycle
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml:ro
- ./rules:/etc/prometheus/rules:ro
- prometheus-data:/prometheus
extra_hosts:
- "host.docker.internal:host-gateway"
restart: unless-stopped
alertmanager:
image: prom/alertmanager:v0.34.1
ports:
- "9093:9093"
volumes:
- ./alertmanager.yml:/etc/alertmanager/alertmanager.yml:ro
- ./secrets:/etc/alertmanager/secrets:ro
restart: unless-stopped
volumes:
prometheus-data:
Retention defaults to 15 days. --storage.tsdb.retention.time and --storage.tsdb.retention.size can be combined, and whichever limit is reached first removes the oldest blocks. --web.enable-lifecycle enables the /-/reload and /-/quit endpoints, which have no authentication or CSRF protection of their own, so keep the port on a private network or put a reverse proxy with authentication in front of it (see the security model).
Validate files before starting the server. promtool ships inside the Prometheus image:
promtool check config prometheus.yml
promtool check rules rules/*.yml
amtool check-config alertmanager.yml
## Kubernetes deployment
For most clusters, install the Prometheus Operator through the kube-prometheus-stack Helm chart. It deploys Prometheus, Alertmanager, kube-state-metrics, node exporter, and default rules, and it discovers scrape targets through ServiceMonitor and PodMonitor resources instead of hand-edited scrape configuration.
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm install kube-prometheus-stack prometheus-community/kube-prometheus-stack \
--namespace monitoring --create-namespace \
--values values.yaml
# values.yaml
prometheus:
prometheusSpec:
retention: 30d
# Select ServiceMonitors and PodMonitors from every namespace,
# not only those labeled with this Helm release.
serviceMonitorSelectorNilUsesHelmValues: false
podMonitorSelectorNilUsesHelmValues: false
storageSpec:
volumeClaimTemplate:
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 50Gi
alertmanager:
alertmanagerSpec:
# Mounted at /etc/alertmanager/secrets/<secret-name>/
secrets:
- alertmanager-slack
config:
global:
resolve_timeout: 5m
route:
receiver: slack
group_by: ['alertname', 'namespace']
group_wait: 30s
group_interval: 5m
repeat_interval: 12h
receivers:
- name: slack
slack_configs:
- api_url_file: /etc/alertmanager/secrets/alertmanager-slack/webhook-url
channel: '#alerts'
send_resolved: true
title: 'Alert: {{ .GroupLabels.alertname }}'
The chart does not run Helm templating over alertmanager.config unless alertmanager.tplConfig is set to true. Placeholders such as {{ .Values.slackWebhook }} therefore reach Alertmanager as literal text, which is why the example reads the webhook URL from a mounted Kubernetes Secret instead.
A PodMonitor tells the operator which pods to scrape and on which named container port:
apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata:
name: user-service
namespace: production
spec:
selector:
matchLabels:
app: user-service
podMetricsEndpoints:
- port: http
path: /metrics
interval: 15s
To run a single Prometheus server without the operator, the manifest below sets up RBAC, a scrape configuration, and a StatefulSet with a persistent volume per replica. A plain Deployment sharing one PersistentVolumeClaim is a poor fit for a database, and the ServiceAccount needs permissions to list the objects that service discovery reads.
apiVersion: v1
kind: ServiceAccount
metadata:
name: prometheus
namespace: monitoring
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: prometheus
rules:
- apiGroups: [""]
resources: ["nodes", "nodes/metrics", "services", "pods"]
verbs: ["get", "list", "watch"]
- apiGroups: ["discovery.k8s.io"]
resources: ["endpointslices"]
verbs: ["get", "list", "watch"]
- nonResourceURLs: ["/metrics"]
verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: prometheus
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: prometheus
subjects:
- kind: ServiceAccount
name: prometheus
namespace: monitoring
---
apiVersion: v1
kind: ConfigMap
metadata:
name: prometheus-config
namespace: monitoring
data:
prometheus.yml: |
global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_configs:
- job_name: kubernetes-apiservers
kubernetes_sd_configs:
- role: endpointslice
scheme: https
tls_config:
ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
authorization:
credentials_file: /var/run/secrets/kubernetes.io/serviceaccount/token
relabel_configs:
- source_labels:
- __meta_kubernetes_namespace
- __meta_kubernetes_service_name
- __meta_kubernetes_endpointslice_port_name
action: keep
regex: default;kubernetes;https
- job_name: kubernetes-cadvisor
kubernetes_sd_configs:
- role: node
scheme: https
metrics_path: /metrics/cadvisor
tls_config:
ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
authorization:
credentials_file: /var/run/secrets/kubernetes.io/serviceaccount/token
relabel_configs:
- action: labelmap
regex: __meta_kubernetes_node_label_(.+)
- job_name: kubernetes-pods
kubernetes_sd_configs:
- role: pod
relabel_configs:
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
action: keep
regex: "true"
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
action: replace
target_label: __metrics_path__
regex: (.+)
- source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
action: replace
regex: ([^:]+)(?::\d+)?;(\d+)
replacement: $1:$2
target_label: __address__
- action: labelmap
regex: __meta_kubernetes_pod_label_(.+)
- source_labels: [__meta_kubernetes_namespace]
target_label: namespace
- source_labels: [__meta_kubernetes_pod_name]
target_label: pod
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: prometheus
namespace: monitoring
spec:
serviceName: prometheus
replicas: 1
selector:
matchLabels:
app: prometheus
template:
metadata:
labels:
app: prometheus
spec:
serviceAccountName: prometheus
securityContext:
runAsNonRoot: true
runAsUser: 65534
fsGroup: 65534
containers:
- name: prometheus
image: prom/prometheus:v3.15.0
args:
- --config.file=/etc/prometheus/prometheus.yml
- --storage.tsdb.path=/prometheus
- --storage.tsdb.retention.time=30d
ports:
- name: web
containerPort: 9090
readinessProbe:
httpGet:
path: /-/ready
port: web
livenessProbe:
httpGet:
path: /-/healthy
port: web
resources:
requests:
cpu: 500m
memory: 2Gi
limits:
memory: 4Gi
volumeMounts:
- name: config
mountPath: /etc/prometheus
- name: data
mountPath: /prometheus
volumes:
- name: config
configMap:
name: prometheus-config
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 50Gi
---
apiVersion: v1
kind: Service
metadata:
name: prometheus
namespace: monitoring
spec:
selector:
app: prometheus
ports:
- name: web
port: 9090
targetPort: web
A few details in that manifest are easy to get wrong:
- →The
prometheus.io/scrape,prometheus.io/path, andprometheus.io/portannotations are not built into Prometheus. They only work because thekubernetes-podsjob above defines relabeling rules that read them. - →The Kubernetes
EndpointsAPI is deprecated from Kubernetes 1.33, and the Prometheus documentation recommends theendpointslicerole instead ofendpoints. EndpointSlice discovery needs thediscovery.k8s.io/v1API, available since Kubernetes 1.21. - →Use
authorization.credentials_filerather than the olderbearer_token_file, which no longer appears in the configuration reference. - →Prometheus 3 sets
GOMEMLIMITandGOMAXPROCSfrom the container limits by default, so a memory limit also tunes Go's garbage collector.
# PromQL
## Basic queries
# Instant vector: the latest sample of every matching series
http_requests_total
# Filter by labels (regex matchers are fully anchored)
http_requests_total{job="application", method="GET"}
http_requests_total{job="application", method=~"GET|POST", status_code!="500"}
# Range vector: all samples in the last five minutes
http_requests_total[5m]
# Per-second average rate of increase of a counter
rate(http_requests_total[5m])
# Total increase over a window
increase(http_requests_total[1h])
rate() handles counter resets and extrapolates to the window edges, and it is the right choice for alerts and for slow-moving counters. irate() uses only the last two samples and is meant for graphing volatile, fast-moving counters. increase() is rate() multiplied by the window length in seconds, which reads better for humans but should not be used in recording rules.
A range window needs at least two samples, so make it several scrape intervals long. Grafana's $__rate_interval variable uses max($__interval + scrape_interval, 4 * scrape_interval) for that reason.
## Aggregation operators
# Total request rate across all series
sum(rate(http_requests_total[5m]))
# Request rate per job
sum by (job) (rate(http_requests_total[5m]))
# Average request duration from a histogram's sum and count
sum(rate(http_request_duration_seconds_sum[5m]))
/ sum(rate(http_request_duration_seconds_count[5m]))
# Highest five-minute load average per instance
max by (instance) (node_load5)
# Number of healthy targets
count(up == 1)
# 95th percentile latency across every instance
histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))
Classic histograms must keep the le label in the by clause when aggregating, otherwise histogram_quantile cannot interpolate across buckets. Averaging pre-computed quantiles such as avg(...{quantile="0.95"}) is statistically wrong, which is why histograms aggregate and summaries do not.
## Advanced queries
# Error ratio as a percentage, per job
sum by (job) (rate(http_requests_total{status_code=~"5.."}[5m]))
/ sum by (job) (rate(http_requests_total[5m])) * 100
# CPU usage percentage per instance
100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)
# Memory usage percentage
(1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) * 100
# Disk usage percentage, ignoring in-memory filesystems
(1 - node_filesystem_avail_bytes{fstype!~"tmpfs|ramfs"}
/ node_filesystem_size_bytes{fstype!~"tmpfs|ramfs"}) * 100
# p95 latency per job
histogram_quantile(0.95,
sum by (le, job) (rate(http_request_duration_seconds_bucket[5m]))
)
# Requests per minute
sum(rate(http_requests_total[5m])) * 60
# Top five routes by request rate
topk(5, sum by (route) (rate(http_requests_total[5m])))
# Filesystems predicted to run out of space within four hours
predict_linear(node_filesystem_avail_bytes{fstype!~"tmpfs|ramfs"}[1h], 4 * 3600) < 0
predict_linear() uses simple linear regression and should only be applied to gauges. The fstype filters matter because node exporter reports every mounted filesystem, including ones that fill by design.
## Native histograms
Classic histograms store one series per bucket, and the bucket boundaries are fixed when the code is written. Native histograms store a whole histogram in a single sample with exponentially spaced buckets, and the histogram guidance recommends them over classic histograms and summaries where they are available. Prometheus 3 treats them as stable, but a scrape job must opt in with scrape_native_histograms: true, and client library support is still limited. With native histograms, aggregation needs no by (le):
histogram_quantile(0.95, sum(rate(http_request_duration_seconds[5m])))
# Exporters
## Node exporter (host metrics)
Node exporter exposes hardware and operating system metrics on port 9100. The Prometheus documentation recommends running the static binary directly on each host (current release: 1.12.1). It is designed to monitor the host it runs on, so running it in a container needs host namespaces and a read-only bind mount of the root filesystem:
docker run -d \
--name node-exporter \
--net=host \
--pid=host \
-v "/:/host:ro,rslave" \
prom/node-exporter:v1.12.1 \
--path.rootfs=/host
Because the container uses the host network, Prometheus reaches it through the host's address (host.docker.internal:9100 in the Compose example above), not through a container name.
Key metrics:
- →
node_cpu_seconds_total: CPU time per core and mode - →
node_memory_MemAvailable_bytes: memory available without swapping - →
node_filesystem_avail_bytes: free space for unprivileged users - →
node_network_receive_bytes_total: bytes received per interface - →
node_network_transmit_bytes_total: bytes transmitted per interface
Collectors are enabled with --collector.<name> and turned off with --no-collector.<name>. The filesystem collector accepts --collector.filesystem.fs-types-exclude and --collector.filesystem.mount-points-exclude to keep container and kubelet mounts out of the data.
## Application instrumentation
The Node.js client library prom-client has been deprecated on npm and replaced by @prometheus-io/client, which moved under the Prometheus organization in version 0.16 (August 2026). The package name and require() path change, and the changelog lists breaking changes such as dropped support for Node.js 16 through 21 and 23, so the supported runtimes are Node.js 22, 24, and 26 and later. The example below was run against Express 5 and exposes the metrics used in the PromQL section.
const express = require('express');
const client = require('@prometheus-io/client');
const app = express();
const register = new client.Registry();
client.collectDefaultMetrics({ register });
const httpRequestDuration = new client.Histogram({
name: 'http_request_duration_seconds',
help: 'Duration of HTTP requests in seconds',
labelNames: ['method', 'route', 'status_code'],
buckets: [0.05, 0.1, 0.25, 0.5, 1, 2.5, 5],
registers: [register],
});
const httpRequestsTotal = new client.Counter({
name: 'http_requests_total',
help: 'Total number of HTTP requests',
labelNames: ['method', 'route', 'status_code'],
registers: [register],
});
const httpRequestsInFlight = new client.Gauge({
name: 'http_requests_in_flight',
help: 'Number of HTTP requests currently being handled',
registers: [register],
});
// Business metric: orders by outcome
const ordersTotal = new client.Counter({
name: 'orders_total',
help: 'Total number of orders',
labelNames: ['status'],
registers: [register],
});
app.use((req, res, next) => {
const stopTimer = httpRequestDuration.startTimer();
httpRequestsInFlight.inc();
res.on('finish', () => {
// Use the route pattern, never the raw path, to keep label cardinality bounded.
const route = req.route ? `${req.baseUrl}${req.route.path}` : 'unmatched';
const labels = { method: req.method, route, status_code: res.statusCode };
stopTimer(labels);
httpRequestsTotal.inc(labels);
httpRequestsInFlight.dec();
});
next();
});
app.get('/metrics', async (req, res) => {
res.set('Content-Type', register.contentType);
res.end(await register.metrics());
});
app.post('/orders', (req, res) => {
// ...create the order, then record the outcome
ordersTotal.inc({ status: 'created' });
res.status(201).json({ ok: true });
});
app.listen(3000);
Two details in that middleware prevent common production problems. Falling back to req.path for unmatched requests would create one time series per unique URL that a scanner or bot requests, so unmatched requests share the label unmatched. And http_requests_in_flight counts requests being handled, which is not the same thing as open connections.
Follow the naming conventions: base units (_seconds, _bytes), a _total suffix on counters, and no label with unbounded values such as user IDs or email addresses.
# Alerting
## Alert rules
Save the rules below as rules/alerts.yml. They use the status_code label from the instrumentation above, and the printf filter keeps the value in annotations readable.
groups:
- name: instance_alerts
rules:
- alert: InstanceDown
expr: up == 0
for: 5m
labels:
severity: critical
annotations:
summary: "Instance {{ $labels.instance }} is down"
description: "{{ $labels.instance }} of job {{ $labels.job }} has been unreachable for more than 5 minutes."
- alert: HighCPUUsage
expr: 100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 80
for: 10m
labels:
severity: warning
annotations:
summary: "High CPU usage on {{ $labels.instance }}"
description: "CPU usage has been above 80% for 10 minutes (current value: {{ $value | printf \"%.1f\" }}%)."
- alert: HighMemoryUsage
expr: (1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) * 100 > 90
for: 5m
labels:
severity: warning
annotations:
summary: "High memory usage on {{ $labels.instance }}"
description: "Memory usage is above 90% (current value: {{ $value | printf \"%.1f\" }}%)."
- alert: DiskSpaceLow
expr: |
node_filesystem_avail_bytes{fstype!~"tmpfs|ramfs"}
/ node_filesystem_size_bytes{fstype!~"tmpfs|ramfs"} * 100 < 10
for: 5m
labels:
severity: warning
annotations:
summary: "Low disk space on {{ $labels.instance }}"
description: "Less than 10% of {{ $labels.mountpoint }} is free (current value: {{ $value | printf \"%.1f\" }}%)."
- alert: DiskWillFillIn4Hours
expr: predict_linear(node_filesystem_avail_bytes{fstype!~"tmpfs|ramfs"}[1h], 4 * 3600) < 0
for: 30m
labels:
severity: warning
annotations:
summary: "{{ $labels.mountpoint }} on {{ $labels.instance }} is predicted to fill within 4 hours"
- name: application_alerts
rules:
- alert: HighErrorRate
expr: |
sum by (job) (rate(http_requests_total{status_code=~"5.."}[5m]))
/ sum by (job) (rate(http_requests_total[5m])) * 100 > 5
for: 5m
labels:
severity: critical
annotations:
summary: "High 5xx error rate for {{ $labels.job }}"
description: "More than 5% of requests are failing (current value: {{ $value | printf \"%.1f\" }}%)."
- alert: HighLatency
expr: |
histogram_quantile(0.95,
sum by (le, job) (rate(http_request_duration_seconds_bucket[5m]))
) > 2
for: 10m
labels:
severity: warning
annotations:
summary: "High latency for {{ $labels.job }}"
description: "The 95th percentile latency is above 2 seconds (current value: {{ $value | printf \"%.2f\" }}s)."
The alerting guidance is to alert on symptoms tied to user pain, such as error ratio and latency, and to treat capacity signals such as disk space as lower-urgency warnings. Each alert needs a for duration so brief blips do not page anyone.
## Alertmanager configuration
The Alertmanager configuration reference marks the match, match_re, source_match, and target_match fields as deprecated in favor of matchers, source_matchers, and target_matchers. Secrets are read from files so they stay out of the configuration file. Prometheus 3 requires Alertmanager 0.16 or later because the v1 API is gone.
# alertmanager.yml
global:
resolve_timeout: 5m
smtp_smarthost: 'smtp.example.com:587'
smtp_from: 'alerts@example.com'
smtp_auth_username: 'alerts@example.com'
smtp_auth_password_file: /etc/alertmanager/secrets/smtp_password
route:
receiver: default
group_by: ['alertname', 'cluster', 'service']
group_wait: 30s # defaults: 30s, 5m, 4h
group_interval: 5m
repeat_interval: 12h
routes:
- matchers:
- severity="critical"
receiver: critical-alerts
- matchers:
- severity="warning"
receiver: warning-alerts
receivers:
- name: default
slack_configs:
- api_url_file: /etc/alertmanager/secrets/slack_webhook
channel: '#alerts'
title: 'Alert: {{ .GroupLabels.alertname }}'
text: '{{ range .Alerts }}{{ .Annotations.description }}{{ end }}'
- name: critical-alerts
slack_configs:
- api_url_file: /etc/alertmanager/secrets/slack_webhook
channel: '#critical-alerts'
title: 'CRITICAL: {{ .GroupLabels.alertname }}'
text: '{{ range .Alerts }}{{ .Annotations.description }}{{ end }}'
pagerduty_configs:
- routing_key_file: /etc/alertmanager/secrets/pagerduty_routing_key
email_configs:
- to: 'oncall@example.com'
- name: warning-alerts
slack_configs:
- api_url_file: /etc/alertmanager/secrets/slack_webhook
channel: '#warnings'
title: 'WARNING: {{ .GroupLabels.alertname }}'
text: '{{ range .Alerts }}{{ .Annotations.description }}{{ end }}'
inhibit_rules:
- source_matchers:
- severity="critical"
target_matchers:
- severity="warning"
equal: ['instance']
A few notes on the changes from older examples:
- →
routing_keyis the field for a PagerDuty Events API v2 integration. The olderservice_keyfield is documented for the legacy "Prometheus" integration type. - →A route stops at the first matching child unless
continue: trueis set. Critical and warning routes are mutually exclusive here, socontinueis not needed. - →The inhibition rule mutes warnings for an instance while a critical alert is firing for the same
instance. Anequallist of['alertname', 'instance']would only inhibit alerts that share the same alert name, which a critical and a warning alert normally do not. - →Test routing before deploying with
amtool config routes test --config.file=alertmanager.yml severity=critical.
# Recording rules
Recording rules precompute expensive expressions so dashboards and alerts query a cheap series. Names follow the level:metric:operations convention from the rules guidance.
# rules/recording.yml
groups:
- name: recording_rules
rules:
- record: job:http_requests:rate5m
expr: sum by (job) (rate(http_requests_total[5m]))
- record: job:http_request_duration_seconds:p95
expr: histogram_quantile(0.95, sum by (le, job) (rate(http_request_duration_seconds_bucket[5m])))
- record: instance:node_cpu_utilization:ratio
expr: 1 - avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m]))
When a ratio is recorded, aggregate the numerator and denominator separately and then divide, instead of averaging per-instance ratios.
# Running Prometheus in production
- →High availability: run two identical Prometheus servers that scrape the same targets and evaluate the same rules. Each sends alerts to every Alertmanager instance directly, not through a load balancer, and Alertmanager de-duplicates the notifications in its cluster.
- →Long-term storage: local TSDB retention is bounded by one disk. Send samples to a remote store such as Thanos, Grafana Mimir, or Cortex with
remote_write, and keep local retention short. Remote write uses snappy-compressed protocol buffers over HTTP. - →Federation: a global Prometheus can scrape aggregated series from per-cluster servers through
/federate, which suits job-level rollups. It is not a way to copy every series. - →Meta-monitoring: alert when Prometheus servers, Alertmanagers, and Pushgateways stop responding, and keep an external probe as a fallback if the internal stack fails entirely.
- →Cardinality control: use
metric_relabel_configsto drop labels or series that are never queried, and review the number of active series regularly. - →Hardening: serve Prometheus over TLS with basic authentication or a reverse proxy, restrict
--web.enable-lifecycleand--web.enable-admin-api, and apply KubernetesNetworkPolicyrules around the monitoring namespace.
For a complete example that combines Prometheus with Kubernetes, Terraform, and a CI/CD pipeline, see the end-to-end DevOps project. Cluster fundamentals are covered in Kubernetes fundamentals, and the systemd commands used to run node exporter on a host are in Linux essentials for DevOps.
# Best practices
## Metric design
- →Use base units and unit suffixes in metric names, and a
_totalsuffix on counters. - →Keep label values bounded. Every unique label combination creates a new time series.
- →Prefer histograms for latency so percentiles can be aggregated across instances.
## Query optimization
- →Use recording rules for expensive, frequently used expressions.
- →Keep range windows no longer than needed, and avoid broad regex matchers.
- →Aggregate histogram buckets with
sum by (le, ...)before callinghistogram_quantile.
## Alerting
- →Alert on symptoms such as error ratio and latency, and keep cause-level alerts as warnings.
- →Include
summaryanddescriptionannotations, and link to a runbook when one exists. - →Group and inhibit alerts in Alertmanager to avoid notification storms.
## Resource management
- →Set retention with
--storage.tsdb.retention.timeand, optionally,--storage.tsdb.retention.size. - →Monitor Prometheus itself: scrape duration, active series, and TSDB head size.
- →Use remote write for data that must outlive local retention.
## Security
- →Enable TLS and authentication, because Prometheus has no built-in access control for its HTTP API.
- →Keep secrets in files or Kubernetes Secrets, not in configuration fields that are visible through the API.
- →Upgrade regularly, and stay on a supported release such as the current LTS.
# Key takeaways
- →Prometheus 3 changed metric name validation,
lelabel formatting, range selector boundaries, and the Alertmanager API, so dashboards and alerts written for 2.x should be re-checked after an upgrade. - →Pin exact image tags such as
prom/prometheus:v3.15.0instead oflatest, and plan upgrades around the six-week release cycle and the 3.13 LTS line. - →Always aggregate classic histogram buckets with
sum by (le, ...)beforehistogram_quantile, and never average pre-computed quantiles. - →Alertmanager configuration should use
matchers,source_matchers, andtarget_matchers, with secrets read from files through the*_filefields. - →On Kubernetes, prefer the Prometheus Operator with
ServiceMonitorandPodMonitorresources, and use theendpointslicediscovery role if scrape configuration is written by hand. - →Prometheus local storage is a single-node database, so production setups need redundant servers and a remote store for long-term retention.
- →The Node.js client library is now published as
@prometheus-io/client, and request metrics must use route patterns rather than raw paths to keep cardinality bounded.
# Further reading
Test yourself: Prometheus Monitoring assessment