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.
/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.
RememberThe most common reason an app does not appear in Prometheus is a
ServiceMonitorthat Prometheus does not select. This lab disables the default label selector so everyServiceMonitorin 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.
helm repo add prometheus-community \ https://prometheus-community.github.io/helm-chartshelm 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# monitoring-values.yamlgrafana: admin: existingSecret: grafana-admin # Credentials come from the Secret above userKey: admin-user passwordKey: admin-passwordprometheus: 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 emptyDirPin the chart version so a later helm upgrade is a deliberate choice.
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 nodeHow to Open Grafana and Use the Built-In Dashboards
The chart ships its own provisioned dashboards, so nothing needs importing.
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 monitoringOpen 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.
# order-api.yamlapiVersion: apps/v1kind: Deploymentmetadata: name: order-api namespace: observability-labspec: 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# order-api-service.yamlapiVersion: v1kind: Servicemetadata: name: order-api namespace: observability-lab labels: app: order-api # The ServiceMonitor selects this labelspec: selector: app: order-api ports: - name: web # Must be a named port port: 8080 targetPort: webHow to Create a ServiceMonitor for Your App
# order-api-servicemonitor.yamlapiVersion: monitoring.coreos.com/v1kind: ServiceMonitormetadata: name: order-api namespace: observability-labspec: selector: matchLabels: app: order-api # Selects the Service by label endpoints: - port: web # The named Service port path: /metrics interval: 15s # Scrape every 15 secondskubectl create namespace observability-labkubectl apply -f order-api.yaml -f order-api-service.yaml -f order-api-servicemonitor.yaml # Send steady traffic so the counters movekubectl 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
kubectl port-forward svc/kube-prometheus-stack-prometheus 9090:9090 -n monitoringOpen 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.
# 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 usessum by (pod) (container_memory_working_set_bytes{namespace="observability-lab", container!=""}) / 1024 / 1024 # Restarts in the last hour: a pod restarting repeatedly is unstableincrease(kube_pod_container_status_restarts_total{namespace="observability-lab"}[1h]) > 3 # Request rate by status code for the sample appsum 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 problemssum 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.
# alertmanager.yamlglobal: resolve_timeout: 5m slack_api_url_file: /etc/alertmanager/secrets/slack-webhook/urlroute: 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 }}'# alertmanager-values.yamlalertmanager: alertmanagerSpec: configSecret: alertmanager-custom-config # Use our config instead of the chart default secrets: - slack-webhook # Mounted under /etc/alertmanager/secrets/# Replace the URL with your real Slack incoming webhookkubectl 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.yamlHow 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.
# lab-test-alert.yamlapiVersion: monitoring.coreos.com/v1kind: PrometheusRulemetadata: name: lab-test-alert namespace: monitoringspec: groups: - name: lab.rules rules: - alert: LabTestAlert expr: vector(1) for: 1m labels: severity: warning annotations: summary: Lab test alert from mumbai-prod-clusterkubectl 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 SlackHow to Clean Up
Helm does not remove PVCs or CRDs, so delete them explicitly to avoid leftover disks and custom resources.
kubectl delete -f lab-test-alert.yamlkubectl delete namespace observability-lab helm uninstall kube-prometheus-stack -n monitoringkubectl delete pvc --all -n monitoringkubectl delete namespace monitoringkubectl get crd -o name | grep monitoring.coreos.com | xargs kubectl deleteProduction Best Practices & Common Pitfalls
Common MistakeScraping 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.
SecurityNever put the Grafana password or a Slack webhook in
--setflags or committed values files. Keep them in Secrets, or in an external secret manager such as AWS Secrets Manager synced with External Secrets Operator.
TipThe chart ships hundreds of ready-made alert rules, such as
KubePodCrashLoopingandKubeNodeNotReady. 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_configsreceiver forseverity = "critical"so an on-call engineer is paged, instead of relying on someone watching a Slack channel. - Upgrade CRDs by hand.
helm upgradedoes 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: 2inprometheusSpec, 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 |