Monitoring Kubernetes with Prometheus

Scrape targets, useful cluster SLIs, recording rules and alerts that page a human only when a human is needed.

Published Jun 16, 202612 min read3 views
  • grafana
  • kubernetes
  • observability
  • prometheus

What to scrape

  • kubelet and cAdvisor for container CPU, memory and restarts.

  • kube-state-metrics for object state — desired vs ready replicas.

  • node-exporter for host CPU, memory, disk and network saturation.

  • Your own applications, exposing a small number of meaningful metrics.

A ServiceMonitor

YAML
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: api
  namespace: payments
  labels: { release: kube-prometheus-stack }
spec:
  selector:
    matchLabels: { app: api }
  endpoints:
    - port: metrics
      interval: 30s
      scrapeTimeout: 10s

Recording rules keep dashboards fast

YAML
groups:
  - name: api.rules
    interval: 30s
    rules:
      - record: job:http_requests:rate5m
        expr: sum by (job) (rate(http_requests_total[5m]))
      - record: job:http_errors:ratio5m
        expr: |
          sum by (job) (rate(http_requests_total{code=~"5.."}[5m]))
            /
          sum by (job) (rate(http_requests_total[5m]))

Alert on symptoms, not causes

YAML
- alert: ApiErrorBudgetBurn
  expr: job:http_errors:ratio5m{job="api"} > 0.02
  for: 10m
  labels: { severity: page }
  annotations:
    summary: "API 5xx ratio above 2% for 10 minutes"
    runbook: "https://docs.internal/runbooks/api-5xx"

- alert: PodCrashLooping
  expr: increase(kube_pod_container_status_restarts_total[15m]) > 3
  for: 5m
  labels: { severity: ticket }

Retention and cardinality

Cardinality, not volume, kills a Prometheus server. Never put a user ID, request ID or pod IP in a label. Use recording rules to pre-aggregate and hand long-term retention to Thanos or a remote-write backend.

Bash
# top 10 metrics by series count
curl -s localhost:9090/api/v1/status/tsdb | jq '.data.seriesCountByMetricName[:10]'
Back to all docs