Skip to main content

Monitoring Kubernetes with Prometheus and Grafana

Deploy Prometheus, Grafana, and Alertmanager on Kubernetes with kube-prometheus-stack, scrape your own app, and send Slack alerts.

52 Terms

Overview and What You Will Learn

Prometheus collects metrics from your cluster and applications, Grafana turns them into dashboards, and Alertmanager routes alerts to people. In this lab, you will install the whole stack with the kube-prometheus-stack Helm chart, scrape a sample application through a ServiceMonitor, write PromQL queries that give correct answers, and send a test alert to Slack.

Why This Matters in Production

Without monitoring, you learn that a cluster is struggling when users complain. During an incident at a company like Swiggy on a busy Friday night, the Grafana dashboard is the first thing every engineer opens, because it shows pod CPU, memory, restarts, and error rates in one place. Without it, finding the failing service takes hours instead of minutes.

Core Principles

Prometheus pulls metrics by scraping HTTP /metrics endpoints on a schedule, stores them in a time-series database, and evaluates alert rules against them. The kube-prometheus-stack chart installs three scrape sources for you: node-exporter for node hardware, kube-state-metrics for Kubernetes object state, and the kubelet's built-in container metrics.

flowchart TD P[App pods
/metrics] -->|Scrape| PR[(Prometheus)] N[node-exporter
per node] -->|Scrape| PR K[kube-state-metrics] -->|Scrape| PR PR --> G[Grafana
dashboards] PR -->|Alerts| AM[Alertmanager] AM --> S([Slack or PagerDuty]) classDef src fill:#475569,color:#FFFFFF classDef store fill:#F97316,color:#FFFFFF classDef ui fill:#326CE5,color:#FFFFFF classDef out fill:#10B981,color:#FFFFFF class P,N,K src class PR store class G,AM ui class S out

Prometheus finds your application through a ServiceMonitor, a custom resource that selects a Kubernetes Service and names the port and path to scrape. The Prometheus Operator watches these objects and updates the Prometheus scrape configuration for you.

Remember

The most common reason an app does not appear in Prometheus is a ServiceMonitor that Prometheus does not select. This lab disables the default label selector so every ServiceMonitor in the cluster is discovered.

Detailed Step-by-Step Practical Lab

How to Install kube-prometheus-stack with Helm

Keep credentials out of --set flags, because they end up in your shell history and in the stored Helm release. Create the Grafana admin credentials as a Secret and reference it from a values file.

Bash
helm repo add prometheus-community \
https://prometheus-community.github.io/helm-charts
helm repo update
kubectl create namespace monitoring
kubectl create secret generic grafana-admin -n monitoring \
--from-literal=admin-user=admin \
--from-literal=admin-password="$(openssl rand -base64 24)"
kubectl get storageclass
YAML
# monitoring-values.yaml
grafana:
admin:
existingSecret: grafana-admin # Credentials come from the Secret above
userKey: admin-user
passwordKey: admin-password
prometheus:
prometheusSpec:
retention: 15d # Keep metrics for 15 days
retentionSize: 40GB # Delete oldest data before the 50Gi disk fills
serviceMonitorSelectorNilUsesHelmValues: false # Discover every ServiceMonitor
podMonitorSelectorNilUsesHelmValues: false # Discover every PodMonitor
ruleSelectorNilUsesHelmValues: false # Discover every PrometheusRule
storageSpec:
volumeClaimTemplate:
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 50Gi # Persistent disk, not emptyDir

Pin the chart version so a later helm upgrade is a deliberate choice.

Bash
CHART_VERSION=$(helm search repo prometheus-community/kube-prometheus-stack \
--output json | jq -r '.[0].version')
echo "Pinned chart version: $CHART_VERSION"
helm install kube-prometheus-stack \
prometheus-community/kube-prometheus-stack \
--namespace monitoring \
--version $CHART_VERSION \
--values monitoring-values.yaml
kubectl get pods -n monitoring
# Expect Running pods for Prometheus, Alertmanager, Grafana,
# kube-state-metrics, the operator, and one node-exporter per node
How to Open Grafana and Use the Built-In Dashboards

The chart ships its own provisioned dashboards, so nothing needs importing.

Bash
kubectl get secret grafana-admin -n monitoring \
-o jsonpath='{.data.admin-password}' | base64 -d; echo
kubectl port-forward svc/kube-prometheus-stack-grafana 3000:80 -n monitoring

Open http://localhost:3000, sign in as admin, and open Dashboards. Start with Kubernetes / Compute Resources / Namespace (Pods) for per-pod CPU and memory, and Node Exporter / Nodes for node health.

How to Deploy an App That Exposes Metrics

The Prometheus example app serves metrics on /metrics and counts requests in http_requests_total. Any real service needs a client library for its language, such as prom-client for Node.js or prometheus_client for Python, to expose the same format.

YAML
# order-api.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: order-api
namespace: observability-lab
spec:
replicas: 2
selector:
matchLabels:
app: order-api
template:
metadata:
labels:
app: order-api
spec:
containers:
- name: order-api
image: quay.io/brancz/prometheus-example-app:v0.3.0
ports:
- name: web # The ServiceMonitor refers to this name
containerPort: 8080
YAML
# order-api-service.yaml
apiVersion: v1
kind: Service
metadata:
name: order-api
namespace: observability-lab
labels:
app: order-api # The ServiceMonitor selects this label
spec:
selector:
app: order-api
ports:
- name: web # Must be a named port
port: 8080
targetPort: web
How to Create a ServiceMonitor for Your App
YAML
# order-api-servicemonitor.yaml
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: order-api
namespace: observability-lab
spec:
selector:
matchLabels:
app: order-api # Selects the Service by label
endpoints:
- port: web # The named Service port
path: /metrics
interval: 15s # Scrape every 15 seconds
Bash
kubectl create namespace observability-lab
kubectl apply -f order-api.yaml -f order-api-service.yaml -f order-api-servicemonitor.yaml
# Send steady traffic so the counters move
kubectl run traffic -n observability-lab --image=curlimages/curl --restart=Never -- \
sh -c 'while true; do curl -s http://order-api:8080/ > /dev/null; sleep 0.2; done'
How to Confirm Prometheus Is Scraping Your App
Bash
kubectl port-forward svc/kube-prometheus-stack-prometheus 9090:9090 -n monitoring

Open http://localhost:9090/targets and look for serviceMonitor/observability-lab/order-api with state UP. Then run up{namespace="observability-lab"} in the Graph tab and expect a value of 1 for each pod.

How to Write PromQL Queries That Give Correct Answers

Each query below fixes a common mistake: aggregate before comparing, and use the right memory metric.

Bash
# CPU used per pod, in cores (container!="" skips the pod-level duplicate series)
sum by (pod) (rate(container_cpu_usage_seconds_total{namespace="observability-lab", container!=""}[5m]))
# Memory per pod in MiB, using the working set that the OOM killer actually uses
sum by (pod) (container_memory_working_set_bytes{namespace="observability-lab", container!=""}) / 1024 / 1024
# Restarts in the last hour: a pod restarting repeatedly is unstable
increase(kube_pod_container_status_restarts_total{namespace="observability-lab"}[1h]) > 3
# Request rate by status code for the sample app
sum by (code) (rate(http_requests_total{namespace="observability-lab"}[5m]))
# Error percentage: sum both sides first, then divide (use your app's 5xx label)
sum(rate(http_requests_total{code=~"5.."}[5m])) / sum(rate(http_requests_total[5m])) * 100
# Node memory used (%)
(1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) * 100
# Pods stuck in Pending, a sign of scheduling problems
sum by (namespace) (kube_pod_status_phase{phase="Pending"})
How to Send Alerts to Slack with a Custom Alertmanager Config

Do not apply a Secret over the chart's own Alertmanager Secret, because helm upgrade overwrites it. Instead, store your config in a separate Secret and point Alertmanager at it. The Slack webhook lives in its own Secret, mounted as a file.

YAML
# alertmanager.yaml
global:
resolve_timeout: 5m
slack_api_url_file: /etc/alertmanager/secrets/slack-webhook/url
route:
receiver: 'null'
group_by: ['alertname', 'namespace']
group_wait: 30s
group_interval: 5m
repeat_interval: 12h
routes:
- receiver: 'null' # Drop always-firing meta alerts
matchers:
- 'alertname =~ "Watchdog|InfoInhibitor"'
- receiver: slack-critical
matchers:
- 'severity = "critical"'
- receiver: slack-warnings
matchers:
- 'severity = "warning"'
receivers:
- name: 'null'
- name: slack-critical
slack_configs:
- channel: '#prod-alerts'
send_resolved: true
title: 'CRITICAL: {{ .GroupLabels.alertname }}'
text: |-
Namespace: {{ .GroupLabels.namespace }}
{{ range .Alerts }}Summary: {{ .Annotations.summary }}
{{ end }}
- name: slack-warnings
slack_configs:
- channel: '#prod-warnings'
send_resolved: true
title: 'WARNING: {{ .GroupLabels.alertname }}'
text: '{{ range .Alerts }}{{ .Annotations.summary }} {{ end }}'
YAML
# alertmanager-values.yaml
alertmanager:
alertmanagerSpec:
configSecret: alertmanager-custom-config # Use our config instead of the chart default
secrets:
- slack-webhook # Mounted under /etc/alertmanager/secrets/
Bash
# Replace the URL with your real Slack incoming webhook
kubectl create secret generic slack-webhook -n monitoring \
--from-literal=url='https://hooks.slack.com/services/T0000000/B0000000/replace-me'
kubectl create secret generic alertmanager-custom-config -n monitoring \
--from-file=alertmanager.yaml
helm upgrade kube-prometheus-stack \
prometheus-community/kube-prometheus-stack \
--namespace monitoring \
--version $CHART_VERSION \
--reuse-values \
--values alertmanager-values.yaml
How to Fire a Test Alert End to End

This rule is always true, so it fires after one minute and proves the path from Prometheus to Alertmanager to Slack.

YAML
# lab-test-alert.yaml
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: lab-test-alert
namespace: monitoring
spec:
groups:
- name: lab.rules
rules:
- alert: LabTestAlert
expr: vector(1)
for: 1m
labels:
severity: warning
annotations:
summary: Lab test alert from mumbai-prod-cluster
Bash
kubectl apply -f lab-test-alert.yaml
kubectl port-forward svc/kube-prometheus-stack-alertmanager 9093:9093 -n monitoring
# Open http://localhost:9093 to see LabTestAlert, then check #prod-warnings in Slack
How to Clean Up

Helm does not remove PVCs or CRDs, so delete them explicitly to avoid leftover disks and custom resources.

Bash
kubectl delete -f lab-test-alert.yaml
kubectl delete namespace observability-lab
helm uninstall kube-prometheus-stack -n monitoring
kubectl delete pvc --all -n monitoring
kubectl delete namespace monitoring
kubectl get crd -o name | grep monitoring.coreos.com | xargs kubectl delete

Production Best Practices & Common Pitfalls

Common Mistake

Scraping every target at a 5-second interval in a large cluster. With hundreds of pods, that multiplies the write load on Prometheus and can make it fall behind on ingestion. Use 15 seconds as the default, and shorten the interval only for a few latency-critical metrics.

Security

Never put the Grafana password or a Slack webhook in --set flags or committed values files. Keep them in Secrets, or in an external secret manager such as AWS Secrets Manager synced with External Secrets Operator.

Tip

The chart ships hundreds of ready-made alert rules, such as KubePodCrashLooping and KubeNodeNotReady. Review them in Status > Rules and tune the thresholds before writing your own.

  • Use persistent storage for Prometheus. With emptyDir, a restart erases all history, leaving gaps in dashboards and making post-incident reviews impossible.
  • Give each team its own dashboard. At a company like Swiggy, each squad links a dashboard to its runbook, so on-call engineers go straight to their service's metrics.
  • Watch metric cardinality. Labels with unbounded values, such as user IDs or request IDs, create a new time series for each value and can exhaust Prometheus memory.
  • Add PagerDuty for critical alerts. Add a pagerduty_configs receiver for severity = "critical" so an on-call engineer is paged, instead of relying on someone watching a Slack channel.
  • Upgrade CRDs by hand. helm upgrade does not update the Prometheus Operator CRDs, so apply them manually, following the chart's upgrade notes for each major version.
  • Make Prometheus highly available for production. Run two replicas with replicas: 2 in prometheusSpec, or use Thanos or Grafana Mimir for long-term storage across clusters.

Quick Reference & Troubleshooting Commands

Command Description
kubectl port-forward svc/kube-prometheus-stack-grafana 3000:80 -n monitoring Open Grafana locally
kubectl port-forward svc/kube-prometheus-stack-prometheus 9090:9090 -n monitoring Open the Prometheus UI and Targets page
kubectl get servicemonitor -A List every ServiceMonitor in the cluster
kubectl get prometheusrule -A List all alert rule objects
kubectl logs prometheus-kube-prometheus-stack-prometheus-0 -n monitoring -c prometheus View Prometheus logs
kubectl logs alertmanager-kube-prometheus-stack-alertmanager-0 -n monitoring -c alertmanager Debug Slack delivery failures

Resources

Velero vs etcd Snapshot: Which Do You Need?

Velero vs etcd Snapshot: Which Do You Need?

Velero and etcd snapshots protect different layers of a Kubernetes cluster. See what each backs up, what each misses, and why most DR needs both.

11 min read•Aug 2026
Istio Ambient vs Linkerd in 2026: Which Mesh?

Istio Ambient vs Linkerd in 2026: Which Mesh?

Istio Ambient cuts the sidecar tax at L4, but L7 adds waypoint hops, and Linkerd stable builds now come from Buoyant. Choose with tests.

11 min read•Aug 2026
Nginx Ingress vs Traefik vs Gateway API in 2026

Nginx Ingress vs Traefik vs Gateway API in 2026

Ingress-NGINX is retired. Compare Traefik and Gateway API controllers as replacements, plus a safe migration plan that avoids outages.

10 min read•Aug 2026
OPA Gatekeeper vs Kyverno: Policy Engine in 2026

OPA Gatekeeper vs Kyverno: Policy Engine in 2026

OPA Gatekeeper vs Kyverno compared for 2026: Rego vs YAML, mutation, reporting, and operations, plus how to pick a Kubernetes policy engine.

10 min read•Aug 2026
Helm vs Kustomize in 2026: Templating vs Patching

Helm vs Kustomize in 2026: Templating vs Patching

Helm vs Kustomize compared for 2026 - templating vs patching, Helm 4's new features, and why most production teams end up running both.

5 min read•Aug 2026
Prometheus vs Datadog vs New Relic: Real Costs

Prometheus vs Datadog vs New Relic: Real Costs

Prometheus, Datadog, and New Relic compared for 2026 - real pricing at scale, hidden cost drivers, and which fits a Kubernetes-heavy stack.

5 min read•Aug 2026
Cluster Autoscaler vs Karpenter for EKS in 2026

Cluster Autoscaler vs Karpenter for EKS in 2026

Cluster Autoscaler vs Karpenter on EKS: scale-up speed, bin-packing, Spot handling, Auto Mode limits and a safe migration path, with v1 NodePool YAML.

11 min read•Aug 2026
GKE vs EKS vs AKS in 2026: Which Fits Your Team?

GKE vs EKS vs AKS in 2026: Which Fits Your Team?

GKE, EKS, and AKS compared for 2026 - control plane pricing, Autopilot vs Karpenter vs Node Auto Provisioning, and which platform actually fits your team.

5 min read•Aug 2026
K3s vs K8s vs MicroK8s: Which Distro in 2026?

K3s vs K8s vs MicroK8s: Which Distro in 2026?

Compare K3s, upstream Kubernetes and MicroK8s on footprint, datastores, HA and updates, and pick the right fit for edge, dev or production.

10 min read•Aug 2026
Canary Deployments with Argo Rollouts & Flagger

Canary Deployments with Argo Rollouts & Flagger

Ship to 5% of users first and auto-rollback on bad metrics: canary deployments on Kubernetes with Argo Rollouts, Flagger, and Gateway API.

11 min read•Jun 2026
OpenTelemetry Explained: Metrics, Logs, Traces

OpenTelemetry Explained: Metrics, Logs, Traces

OpenTelemetry in practice: instrument a Node.js service, run a production Collector, sample traces and link metrics, logs and traces in Grafana.

11 min read•Jun 2026
Kubernetes Cost Optimization Without SLO Risk

Kubernetes Cost Optimization Without SLO Risk

Kubernetes clusters average about 8% CPU use. Cut waste safely with request rightsizing, autoscaling, spot, and OpenCost, keeping SLOs.

11 min read•Jun 2026
ArgoCD vs FluxCD: GitOps for Kubernetes in 2026

ArgoCD vs FluxCD: GitOps for Kubernetes in 2026

ArgoCD vs FluxCD compared for 2026: UI, multi-tenancy, Helm, image automation and pruning risks, with a clear guide to picking your GitOps engine.

10 min read•Jun 2026

Explore More in Kubernetes Networking and Traffic Management

All 6 Topics

Frequently Asked Questions

Is Monitoring Kubernetes with Prometheus and Grafana free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Monitoring Kubernetes with Prometheus and Grafana topic cover?

Deploy Prometheus, Grafana, and Alertmanager on Kubernetes with kube-prometheus-stack, scrape your own app, and send Slack alerts.

Does Monitoring Kubernetes with Prometheus and Grafana include hands-on modules?

Yes - this topic has 2 attached modules for hands-on practice.

Found a mistake, an outdated step or a broken link?