Kubernetes Monitoring
Monitor Kubernetes with metrics-server, Prometheus, Grafana and kube-state-metrics, plus logging, tracing, alerting and the golden signals.
Monitoring tells you whether your applications and the cluster they run on are healthy, and gives you the data to find out why when they are not. In Kubernetes, workloads are short-lived and move between nodes, so monitoring must discover targets dynamically and attach labels such as namespace, pod and deployment to every signal.
The Three Pillars of Observability
| Pillar | Question it answers | Typical tools |
|---|---|---|
| Metrics | How much, how fast, how often? | Prometheus, Grafana, metrics-server |
| Logs | What happened, and in what order? | Fluent Bit, Loki, Elasticsearch, OpenSearch |
| Traces | Where did the time go across services? | OpenTelemetry, Jaeger, Tempo |
Metrics are cheap and good for alerting. Logs give detail for debugging. Traces connect a single request across many microservices.
What to Monitor
Monitor at four levels:
- Cluster: node health, control plane components, API server latency, etcd health.
- Nodes: CPU, memory, disk, network, and node conditions such as
DiskPressureandMemoryPressure. - Kubernetes objects: Pod phase, restarts, Deployment replica counts, Job success, PVC status.
- Application: request rate, errors, latency, JVM heap and GC, connection pool usage, business metrics.
Core Monitoring Components
metrics-server
metrics-server collects CPU and memory usage from each kubelet and exposes it through the Metrics API. It powers kubectl top and the Horizontal Pod Autoscaler. It keeps only recent values and is not a long-term monitoring system.
kubectl top nodes
# NAME CPU(cores) CPU% MEMORY(bytes) MEMORY%
# node-1 312m 15% 2104Mi 54%
kubectl top pods -n production --sort-by=memory
# NAME CPU(cores) MEMORY(bytes)
# orders-7c9d8f6b5d-x2k4p 85m 412Mi
kube-state-metrics
kube-state-metrics listens to the API server and turns object state into metrics, for example kube_deployment_status_replicas_available or kube_pod_container_status_restarts_total. It reports what Kubernetes believes the state is, not resource usage.
node-exporter
node-exporter runs as a DaemonSet and exposes host-level metrics such as CPU, memory, disk and network for each node.
Prometheus
Prometheus is a time-series database that pulls (scrapes) metrics over HTTP, stores them, and evaluates alert rules. In Kubernetes it uses service discovery to find Pods and Services automatically.
Grafana
Grafana queries Prometheus (and Loki or Tempo) and shows dashboards. It does not store metrics itself.
Installing the Stack with Helm
The kube-prometheus-stack chart installs Prometheus, Alertmanager, Grafana, kube-state-metrics, node-exporter and a set of default dashboards and alert rules.
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update
helm install monitoring prometheus-community/kube-prometheus-stack \
--namespace monitoring --create-namespace
kubectl get pods -n monitoring
Scraping a Spring Boot Application
Expose Prometheus metrics from Spring Boot with Actuator and Micrometer:
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
# application.yml
management:
endpoints:
web:
exposure:
include: health,prometheus
With the Prometheus Operator (installed by kube-prometheus-stack), tell Prometheus what to scrape using a ServiceMonitor:
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: orders
namespace: monitoring
labels:
release: monitoring # must match the Prometheus serviceMonitorSelector
spec:
namespaceSelector:
matchNames: [production]
selector:
matchLabels:
app: orders # labels on the Service, not the Pod
endpoints:
- port: http # named port on the Service
path: /actuator/prometheus
interval: 30s
Useful PromQL Queries
# Request rate per second, per service
sum(rate(http_server_requests_seconds_count[5m])) by (service)
# Error ratio (5xx share of all requests)
sum(rate(http_server_requests_seconds_count{status=~"5.."}[5m]))
/ sum(rate(http_server_requests_seconds_count[5m]))
# 95th percentile latency
histogram_quantile(0.95,
sum(rate(http_server_requests_seconds_bucket[5m])) by (le))
# Containers restarting
increase(kube_pod_container_status_restarts_total[1h]) > 3
Alerting
Prometheus evaluates alert rules and sends firing alerts to Alertmanager, which groups, deduplicates, silences and routes them to Slack, email or PagerDuty.
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: orders-alerts
namespace: monitoring
labels:
release: monitoring
spec:
groups:
- name: orders
rules:
- alert: HighErrorRate
expr: |
sum(rate(http_server_requests_seconds_count{status=~"5..",app="orders"}[5m]))
/ sum(rate(http_server_requests_seconds_count{app="orders"}[5m])) > 0.05
for: 10m
labels:
severity: critical
annotations:
summary: "Orders error rate above 5% for 10 minutes"
Alert on symptoms users feel (errors, latency, saturation), not on every internal cause.
The Golden Signals
Google's SRE guidance suggests watching four signals for any service:
| Signal | Meaning | Example metric |
|---|---|---|
| Latency | Time to serve a request | p95 request duration |
| Traffic | Demand on the system | Requests per second |
| Errors | Rate of failed requests | 5xx ratio |
| Saturation | How full the resource is | CPU throttling, memory use vs limit |
Logging in Kubernetes
Containers should write logs to stdout and stderr. The container runtime stores them on the node, and kubectl logs reads them. Because Pod logs disappear when the Pod is deleted, run a log collector as a DaemonSet (Fluent Bit or Vector) that ships logs to central storage such as Loki or Elasticsearch.
kubectl logs deploy/orders -n production --tail=100
kubectl logs orders-7c9d8f6b5d-x2k4p --previous # logs of the crashed container
kubectl logs -l app=orders --all-containers=true --since=15m
Prefer structured JSON logs with a correlation ID so a request can be followed across services.
Common Mistakes
- No resource requests on Pods. Without requests, CPU and memory percentages are meaningless and the HPA cannot work.
- High-cardinality labels. Putting user IDs or request IDs in metric labels creates millions of series and can crash Prometheus.
- Alerting on everything. Too many alerts cause alert fatigue, and real incidents get ignored.
- Treating metrics-server as monitoring. It has no history and no alerting.
- Keeping logs only on the node. Logs are lost when a Pod is rescheduled or a node is replaced.
Best Practices
- Install a full stack (Prometheus, Alertmanager, Grafana, kube-state-metrics, node-exporter) rather than metrics-server alone.
- Expose application metrics with Micrometer and scrape them with a
ServiceMonitor. - Define alerts around the golden signals and add a
for:duration to avoid flapping. - Send logs to central storage and use structured logging with correlation IDs.
- Set retention and storage for Prometheus on a persistent volume, or use remote storage such as Thanos or Mimir for long-term data.
Interview Questions
1. What is the difference between metrics-server and Prometheus?
metrics-server provides current CPU and memory usage through the Metrics API for kubectl top and the HPA, with no history. Prometheus is a full monitoring system that scrapes many kinds of metrics, stores them as time series, runs queries and evaluates alert rules.
2. What does kube-state-metrics do, and how is it different from node-exporter?
kube-state-metrics converts the state of Kubernetes objects (replica counts, Pod phases, restarts) into metrics. node-exporter exposes hardware and OS metrics of each node. One describes object state, the other describes machine resources.
3. How does Prometheus find Pods to scrape in Kubernetes?
It uses Kubernetes service discovery, watching the API server for Pods, Services and Endpoints. With the Prometheus Operator you declare targets using ServiceMonitor or PodMonitor resources, and the operator generates the scrape configuration.
4. How would you monitor a Spring Boot application on Kubernetes?
Add Actuator and the Micrometer Prometheus registry, expose /actuator/prometheus, create a ServiceMonitor so Prometheus scrapes it, and build Grafana dashboards for request rate, errors, latency, JVM memory and GC. Add alerts on error rate and latency.
5. What are the four golden signals?
Latency, traffic, errors and saturation. They give a compact view of service health from the user's point of view.
6. Why should containers log to stdout instead of files?
The container runtime captures stdout and stderr, so kubectl logs and log collectors can read them without extra configuration. Log files inside the container are lost with the container and need extra volumes and agents.
7. A dashboard shows memory near the limit. What do you check?
Compare usage against the container memory limit, check for OOMKilled in kubectl describe pod, review JVM settings such as -XX:MaxRAMPercentage, look at the memory growth trend for leaks, and then adjust limits or fix the leak.
Summary
- Use all three pillars: metrics for alerting, logs for detail, traces for request flow.
metrics-serverpowerskubectl topand the HPA, while Prometheus handles storage, queries and alerts.- Scrape applications with a
ServiceMonitor, and alert on the golden signals. - Ship logs to central storage and avoid high-cardinality metric labels.
Continue Learning
Previous: Spring Boot on Kubernetes | Next: Kubernetes Troubleshooting
Was this guide helpful?
CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.