Kubernetes Observability

How to Monitor a Kubernetes Cluster with Prometheus

November 28, 2026
7
min read
Kubernetes Observability

A Kubernetes pod can fail and be replaced before you investigate what went wrong. By then, the cluster may look healthy again, but its current state won’t tell you whether rising memory usage, CPU throttling, or repeated restarts preceded the failure. Prometheus helps you investigate these problems by collecting and retaining metrics from nodes, containers, Kubernetes objects, and applications. Its Kubernetes service discovery also keeps scrape targets up to date as workloads scale, restart, or move between nodes.

You can set up this monitoring using kube-prometheus-stack, which deploys Prometheus, the Prometheus Operator, Grafana, Alertmanager, and Kubernetes metric exporters through Helm. This guide explains how these components work together and walks you through installing the stack, monitoring custom applications with ServiceMonitors, building Grafana dashboards, and configuring alerts. You’ll also learn how to verify metric collection, troubleshoot failures, and manage storage, security, and scaling in production.

How Prometheus Monitors a Kubernetes Cluster

Prometheus relies on Kubernetes components and exporters to expose metrics. It collects these metrics at regular intervals, stores them as time series, and makes them available for queries and alerts. The Prometheus Operator manages the scrape configuration, while Grafana and Alertmanager provide dashboards and notifications.

How Prometheus Discovers and Scrapes Targets

Prometheus collects metrics by sending HTTP requests to targets that expose a metrics endpoint, usually /metrics. Each scrape returns measurements identified by a metric name and labels such as namespace, pod, and container. Prometheus stores these samples in its time-series database (TSDB), where you can use PromQL to examine resource usage, performance trends, and failures over time.

Because Kubernetes pods can be replaced or rescheduled, Prometheus uses service discovery to track their changing endpoints through the Kubernetes API. With the Prometheus Operator, you configure scraping through ServiceMonitor resources that select Services or PodMonitor resources that select pods. The Operator generates the corresponding scrape configuration without requiring you to maintain target addresses manually. The stack uses a default scrape interval of 30 seconds, which you can override for individual targets.

Where Kubernetes Metrics Come From

Different components expose different aspects of cluster health and resource usage:

Metric SourceWhat It MeasuresExample Metrics
node-exporterNode CPU, memory, disk, filesystem, and network usagenode_cpu_seconds_total, node_memory_MemAvailable_bytes
kube-state-metricsKubernetes object state, including deployment replicas, pod restarts, and resource requestskube_deployment_status_replicas_available, kube_pod_container_status_restarts_total
kubelet/cAdvisorActual container CPU usage, memory working set, and throttlingcontainer_cpu_usage_seconds_total, container_memory_working_set_bytes
Control-plane componentsAPI server requests, scheduling activity, and other control-plane operationsapiserver_request_total, scheduler_pending_pods

These sources complement one another. For example, kube-state-metrics exposes a container’s configured memory request, while cAdvisor reports its actual memory working set. Comparing them helps you understand resource consumption relative to requested capacity. node-exporter provides the node-level metrics needed to determine whether the underlying host is also running low on resources.

On managed Kubernetes services such as EKS, GKE, and AKS, some control-plane endpoints may not be accessible to an in-cluster Prometheus server. You’ll need to account for those restrictions when verifying scrape targets.

How the Prometheus Operator, Grafana, and Alertmanager Work Together

The Prometheus Operator manages monitoring components through Kubernetes custom resource definitions (CRDs). The kube-prometheus-stack Helm chart installs the Operator alongside Prometheus, Grafana, Alertmanager, metric exporters, and preconfigured dashboards and alert rules.

The main custom resources are:

  • Prometheus and Alertmanager: Define the monitoring servers, including their replicas, storage, and configuration.
  • ServiceMonitor and PodMonitor: Specify which Services or pods Prometheus should scrape and how.
  • PrometheusRule: Defines recording rules and alert conditions evaluated by Prometheus.
  • AlertmanagerConfig: Defines alert routing and notification receivers such as Slack and PagerDuty.

Prometheus collects metrics and evaluates alert rules, while Grafana queries the stored data to display dashboards. When an alert fires, Prometheus sends it to Alertmanager, which groups related alerts and routes notifications to the configured receivers.

You can add applications to Prometheus by creating ServiceMonitor resources without manually editing prometheus.yml.

How to Install kube-prometheus-stack with Helm

You can install Prometheus and its supporting monitoring components using the kube-prometheus-stack Helm chart. It deploys Prometheus, the Prometheus Operator, Grafana, Alertmanager, and Kubernetes metric exporters.

We’ll use chart version 93.4.0, the Helm release name monitoring, and the namespace monitoring throughout the setup. Keep these names consistent because the commands and monitoring resources later in the guide depend on them.

Step 1: Check the Kubernetes Prerequisites

Before installing Prometheus, make sure you have a running Kubernetes cluster, Helm, and kubectl configured to access the cluster. You’ll also need permissions to create cluster-scoped resources, including custom resource definitions (CRDs) and RBAC objects.

The chart version used here requires Kubernetes 1.25 or later.

Run the following commands to check your environment:

kubectl cluster-info
kubectl get nodes
kubectl get storageclass
helm version

Start by confirming that kubectl cluster-info can reach the Kubernetes API server and that your nodes report Ready.

Next, check the available StorageClasses. You’ll use one to provision persistent volumes for Prometheus, Alertmanager, and Grafana. If your cluster has a default StorageClass, Kubernetes can provision these volumes automatically. Otherwise, note the name of an available class so you can specify it in the next step.

Step 2: Configure Prometheus Storage and Retention

Prometheus stores collected metrics in a local time-series database (TSDB). Without persistent storage, you lose that history when its Pod is removed or replaced. Configure storage before installing the stack to preserve the metrics you’ll use for dashboards and troubleshooting.

Create a file named values.yaml in your working directory and add:

prometheus:
  prometheusSpec:
    retention: 15d
    retentionSize: 40GB
    resources:
      requests:
        cpu: 500m
        memory: 2Gi
    storageSpec:
      volumeClaimTemplate:
        spec:
          accessModes:
            - ReadWriteOnce
          resources:
            requests:
              storage: 50Gi

alertmanager:
  alertmanagerSpec:
    storage:
      volumeClaimTemplate:
        spec:
          accessModes:
            - ReadWriteOnce
          resources:
            requests:
              storage: 2Gi
    alertmanagerConfigSelector:
      matchLabels:
        alertmanagerConfig: slack

grafana:
  persistence:
    enabled: true
    size: 10Gi

This configuration allocates a 50Gi persistent volume to Prometheus and retains metrics for up to 15 days or until the storage-size limit of 40GB is reached, whichever comes first. The remaining space accommodates the write-ahead log (WAL) and temporary disk usage during compaction. Leave approximately 15–20% of the allocated disk outside the Prometheus retention-size limit.

The CPU and memory requests establish an initial resource allocation for Prometheus. Adjust them as your monitoring workload grows.

Alertmanager receives persistent storage for its state, while Grafana gets a separate volume to preserve dashboards and configuration saved through its interface.

If your cluster has no default StorageClass, add storageClassName under both volumeClaimTemplate.spec blocks and set grafana.persistence.storageClassName to the class you identified earlier.

The configuration also prepares Alertmanager to load the Slack notification route we’ll create later. For custom application monitoring and alert rules, you’ll use the label release: monitoring on ServiceMonitor, PodMonitor, and PrometheusRule resources so the deployed Prometheus instance selects them.

Step 3: Install kube-prometheus-stack

With your configuration ready, add the Prometheus Community Helm repository and update its chart index:

helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update

From the directory containing values.yaml, install the stack:

helm upgrade --install monitoring prometheus-community/kube-prometheus-stack \
  --namespace monitoring \
  --create-namespace \
  --version 93.4.0 \
  -f values.yaml

Helm creates the monitoring namespace if it doesn’t exist, installs the monitoring components, and applies your storage and retention settings. You can use the same upgrade --install command when changing the configuration later.

Once the installation finishes, check the Helm release and Kubernetes resources:

helm status monitoring -n monitoring
kubectl get pods -n monitoring
kubectl get pvc -n monitoring

The Helm release should report deployed. After the workloads become ready, you should see Prometheus, Alertmanager, Grafana, the Prometheus Operator, kube-state-metrics, and node-exporter. The node-exporter DaemonSet runs on eligible Linux nodes to collect node-level metrics.

Check that the persistent volume claims report Bound. This confirms Kubernetes has provisioned the storage needed by the monitoring components.

If a claim remains Pending, inspect it:

kubectl describe pvc <pvc-name> -n monitoring

Look at the Events section for provisioning errors. An unavailable storage provisioner or incorrect StorageClass can prevent stateful components from starting.

Step 4: Access Prometheus and Grafana

You can access both monitoring interfaces using kubectl port-forward without exposing them publicly.

In your first terminal, forward the Prometheus Service to port 9090:

kubectl port-forward -n monitoring svc/monitoring-kube-prometheus-prometheus 9090:9090

Leave that terminal running. In a second terminal, forward Grafana to port 3000:

kubectl port-forward -n monitoring svc/monitoring-grafana 3000:80

Open http://localhost:9090 for Prometheus and http://localhost:3000 for Grafana.

Grafana uses admin as its default username. Retrieve the generated password from its Kubernetes Secret:

kubectl get secret monitoring-grafana -n monitoring \
  -o jsonpath='{.data.admin-password}' | base64 --decode

Sign in using the retrieved password. The Helm chart provisions a Prometheus data source and Kubernetes dashboards, so you can start exploring cluster metrics without manually connecting Grafana to Prometheus.

Keep the port-forward sessions running while using the interfaces. For production access, configure authentication and appropriate network restrictions instead of relying on local port-forwarding.

Verify That Prometheus Is Collecting Kubernetes Metrics

A successful installation confirms that the monitoring components were deployed, but you still need to check whether Prometheus is collecting the expected Kubernetes metrics. Start by verifying target discovery and scrape health, then query the collected data to make sure it is available for monitoring.

Check Target Discovery and Scrape Health

With the Prometheus port-forward running, open http://localhost:9090/targets. You can also reach this page through Status → Target health in the Prometheus interface.

Look for targets associated with node-exporter, kube-state-metrics, the kubelet, and the Kubernetes API server. Each discovered target has a health status:

  • UP: Prometheus successfully completed the most recent scrape.
  • DOWN: Prometheus discovered the target but couldn’t scrape it successfully.

If a target is DOWN, inspect its last error. Connection failures can indicate an unreachable endpoint or incorrect port, while HTTP errors may point to authentication or endpoint configuration problems.

If an expected target doesn’t appear, open Status → Service discovery. This page shows discovered targets and helps you determine whether discovery rules removed them. Missing targets often indicate a ServiceMonitor selector or Service configuration problem rather than a failed scrape.

Confirm Metrics Are Being Collected with PromQL

Next, use the Prometheus query interface to confirm that successful scrapes are producing metrics.

Start by running:

sum by (job) (up)

Prometheus generates the up metric for each scrape target. A value of 1 means the latest scrape succeeded, while 0 means it failed. Summing these values by job gives you the number of successfully scraped targets for each monitoring component.

For example, if the node-exporter job returns 3, Prometheus is successfully collecting metrics from three node-exporter targets. Compare that count with the number of eligible nodes in your cluster.

To identify failed targets, run:

up == 0

This returns targets whose latest scrapes failed. If it returns no results, there are no currently failing discovered targets. However, you should still confirm that all the targets you expect have been discovered.

Next, check whether Prometheus is receiving metrics from the main Kubernetes sources. Run these queries individually:

node_cpu_seconds_total

This returns CPU time counters exposed by node-exporter. You should see time series with labels identifying nodes, CPUs, and CPU modes.

kube_node_info

This retrieves Kubernetes node information collected by kube-state-metrics.

container_cpu_usage_seconds_total

This returns container CPU usage counters exposed through the kubelet’s cAdvisor metrics endpoint.

You can verify that Prometheus is successfully scraping that endpoint with:

up{job="kubelet", metrics_path="/metrics/cadvisor"}

Each successfully scraped kubelet target should return 1. Together, these checks establish whether Prometheus is receiving node, Kubernetes object, and container metrics.

Resolve Missing or Unavailable Targets

If a target is missing, start by checking the ServiceMonitor resources and their labels:

kubectl get servicemonitors -A --show-labels

Confirm that the expected ServiceMonitor exists and that its labels match the Prometheus instance’s selector. For the setup in this guide, custom ServiceMonitors need the label release: monitoring.

If the monitor exists but its target is missing, check whether it selects the intended Service and whether that Service has ready endpoints. If the target appears but reports up=0, investigate its port, metrics path, network connectivity, and authentication.

Managed Kubernetes clusters require additional attention because providers control access to some control-plane components. On EKS, GKE, and AKS, scheduler, controller-manager, or etcd metrics may not be accessible from an in-cluster Prometheus instance.

If your cluster doesn’t expose those metrics, disable the affected monitoring components rather than leaving permanently unavailable targets in your setup.

Add the applicable settings to your existing values.yaml:

kubeScheduler:
  enabled: false

kubeControllerManager:
  enabled: false

kubeEtcd:
  enabled: false

Only disable components whose metrics you cannot access. The chart’s corresponding bundled monitoring rules are also disabled when these components are turned off.

Apply the changes to your existing Helm release:

helm upgrade monitoring prometheus-community/kube-prometheus-stack \
  --namespace monitoring \
  --version 93.4.0 \
  -f values.yaml

Return to Prometheus and inspect the targets and alerts again. Confirm that the monitoring components you expect to scrape are healthy and that alerts for unavailable control-plane targets are no longer active.

Once Prometheus is collecting the expected infrastructure metrics, you can extend the setup to monitor your own applications using ServiceMonitors and PodMonitors.

Monitor Your Applications with ServiceMonitor and PodMonitor

Prometheus can now collect infrastructure metrics, but you also need application metrics to monitor request rates, errors, and response times. Your application must expose these metrics through an HTTP endpoint, usually /metrics, using a Prometheus client library or exporter.

You can then use a ServiceMonitor to tell Prometheus which application endpoints to scrape. We’ll deploy a sample application that already exposes Prometheus metrics, connect it to the monitoring stack, and verify that its metrics are being collected.

Create a ServiceMonitor for Your Application

We’ll use a sample HTTP application that exposes request counters and duration metrics on port 8080. To monitor its replicas, you need three resources: a Deployment to run the application, a Service to expose its metrics endpoint, and a ServiceMonitor to configure Prometheus scraping.

Create a file named example-app.yaml:

apiVersion: v1
kind: Namespace
metadata:
  name: demo
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: example-app
  namespace: demo
spec:
  replicas: 2
  selector:
    matchLabels:
      app: example-app
  template:
    metadata:
      labels:
        app: example-app
    spec:
      containers:
        - name: example-app
          image: quay.io/brancz/prometheus-example-app:v0.5.0
          ports:
            - name: web
              containerPort: 8080
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              memory: 256Mi
---
apiVersion: v1
kind: Service
metadata:
  name: example-app
  namespace: demo
  labels:
    app: example-app
spec:
  selector:
    app: example-app
  ports:
    - name: web
      port: 8080
      targetPort: web
---
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: example-app
  namespace: demo
  labels:
    release: monitoring
spec:
  selector:
    matchLabels:
      app: example-app
  endpoints:
    - port: web
      path: /metrics

The Deployment creates two application replicas. The Service selects those pods using app: example-app, while the ServiceMonitor selects the Service using the same label on the Service’s metadata.

Two other settings connect this configuration to Prometheus. The ServiceMonitor’s release: monitoring label allows the Prometheus instance installed earlier to discover it, and endpoints.port: web identifies the named Service port to scrape. Prometheus uses the configured /metrics path and the stack’s default scrape interval.

Apply the manifest:

kubectl apply -f example-app.yaml

Wait for the application replicas to become ready:

kubectl rollout status deployment/example-app -n demo

Next, confirm that the Service has endpoints:

kubectl get endpointslices -n demo \
  -l kubernetes.io/service-name=example-app

Once both replicas are ready, the Service should have endpoints corresponding to their pods. Prometheus can use these endpoints to scrape each replica separately.

Verify application metric collection

Open the Prometheus Status → Target health page and find the targets associated with the demo/example-app ServiceMonitor. You should see two targets, one per application replica, reporting UP.

Figure: Prometheus showing both example-app scrape targets in the UP state

You can confirm this with PromQL:

up{namespace="demo", service="example-app"}

Two series with values of 1 indicate that Prometheus is successfully scraping both replicas.

Figure: PromQL results showing successful scrapes from both example-app replicas

To check application-specific metrics, generate a request. In another terminal, forward the example application’s Service:

kubectl port-forward -n demo svc/example-app 8080:8080

Leave the port-forward running, then send a request:

curl http://localhost:8080/

The sample application records HTTP request metrics. After the next scrape, query:

http_requests_total{namespace="demo", service="example-app"}

You should see an HTTP request counter for the replica that handled the request. This verifies that Prometheus is collecting application-generated metrics, not just reporting the endpoint as reachable.

If the application doesn’t appear under Target health, check the ServiceMonitor’s release label, its Service selector, and the Service endpoints. If the target appears but reports DOWN, check that the application exposes /metrics on the configured port.

For your own applications, replace the sample image with your instrumented service and update the Deployment, Service, and ServiceMonitor selectors and port names accordingly.

When to Use PodMonitor Instead

A PodMonitor lets Prometheus scrape pods directly without requiring a Service. It’s useful for workloads such as queue consumers and background workers that expose metrics but don’t need a Service for application traffic.

For example, you could monitor the sample application’s pods directly with the following resource:

apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata:
  name: example-app-pods
  namespace: demo
  labels:
    release: monitoring
spec:
  selector:
    matchLabels:
      app: example-app
  podMetricsEndpoints:
    - port: web
      path: /metrics

Here, spec.selector matches pod labels rather than Service labels, and podMetricsEndpoints.port refers to the named container port.

This is an alternative to the ServiceMonitor above, not an additional requirement. If you want to test it, remove the existing ServiceMonitor before applying the PodMonitor so Prometheus doesn’t scrape the same pods twice:

kubectl delete servicemonitor example-app -n demo

Save the PodMonitor as example-app-podmonitor.yaml and apply it:

kubectl apply -f example-app-podmonitor.yaml

Return to Prometheus Target health and confirm that the PodMonitor discovers and successfully scrapes both application replicas.

After testing the PodMonitor, restore the original ServiceMonitor before continuing with the tutorial:

kubectl delete podmonitor example-app-pods -n demo
kubectl apply -f example-app.yaml

This restores the service="example-app" label used by the PromQL queries in the following sections.

For services that already have Kubernetes Service objects, a ServiceMonitor is generally the simpler choice. Use PodMonitor when you need to discover pods directly.

Visualize Kubernetes Metrics with Grafana and PromQL

Now that Prometheus is collecting infrastructure and application metrics, you can use Grafana to visualize resource usage, identify performance trends, and investigate failures. The kube-prometheus-stack installation already configures Grafana with a Prometheus data source and Kubernetes dashboards, so you don’t need to connect them manually.

Explore the Preconfigured Kubernetes Dashboards

Open Grafana at http://localhost:3000, select Dashboards, and search for Kubernetes. You’ll find dashboards for cluster resources, nodes, namespaces, and workloads.

Start with Kubernetes / Compute Resources / Cluster to examine cluster-wide CPU and memory utilization, resource requests, and limits. This gives you an overview of cluster resource consumption before investigating individual workloads.

Figure: Grafana’s Kubernetes cluster dashboard showing CPU and memory utilization

Next, open Kubernetes / Compute Resources / Namespace (Pods) and select demo from the namespace filter to examine pod-level resource consumption. You can use these views to identify which workloads consume the most CPU and memory.

Figure: Grafana showing CPU and memory utilization for pods in the demo namespace

You can also adjust the time range to investigate changes before an incident. For example, selecting the last six hours lets you compare current resource usage with earlier activity.

Build a Dashboard with PromQL

The preconfigured dashboards cover common Kubernetes metrics, but you can create your own panels to monitor specific applications or workloads.

In Grafana, select Dashboards → New → New dashboard, then Add visualization. Choose the Prometheus data source and open the query editor.

Start with a panel that displays CPU usage per pod. Enter this PromQL expression:

sum by (namespace, pod) (
  rate(container_cpu_usage_seconds_total{
    job="kubelet",
    metrics_path="/metrics/cadvisor",
    container!="",
    image!=""
  }[5m])
)

The rate() function calculates average CPU usage per second over a five-minute window. Summing by namespace and pod combines CPU consumption across the containers in each pod.

The result is measured in CPU cores. For example, 0.5 means a pod used the equivalent of half a CPU core on average during that window.

Select a Time series visualization, name the panel Pod CPU Usage, and set its unit to CPU cores. Save the panel and dashboard.

You can now add the following queries as separate panels to monitor other aspects of Kubernetes health.

Pod Memory Usage

sum by (namespace, pod) (
  container_memory_working_set_bytes{
    job="kubelet",
    metrics_path="/metrics/cadvisor",
    container!="",
    image!=""
  }
)

This query shows each pod’s memory working set in bytes. Use a Time series visualization with a bytes unit to identify workloads whose memory consumption is increasing.

Compare memory usage against configured limits when investigating possible out-of-memory failures. A memory request controls scheduling, while a memory limit determines when Kubernetes can enforce the container’s memory ceiling.

CPU Throttling

sum by (namespace, pod) (
  rate(container_cpu_cfs_throttled_periods_total{
    job="kubelet",
    metrics_path="/metrics/cadvisor",
    container!=""
  }[5m])
)
/
sum by (namespace, pod) (
  rate(container_cpu_cfs_periods_total{
    job="kubelet",
    metrics_path="/metrics/cadvisor",
    container!=""
  }[5m])
)

This calculates the proportion of CPU enforcement periods in which containers were throttled. A value of 0.3 means throttling occurred during 30% of those periods, not that the workload lost 30% of its CPU time.

Use it alongside CPU usage and application latency to investigate whether CPU limits are affecting performance. Set the Grafana unit to Percent (0.0–1.0).

Container Restarts

increase(kube_pod_container_status_restarts_total[1h]) > 0

This query identifies containers with restart activity during the last hour. Use a table visualization to find the affected namespaces, pods, and containers.

The increase() function estimates counter changes over the selected interval, so the result is useful for detecting restarts rather than obtaining an exact event count.

Application Request Rate

You can also monitor the example application deployed earlier:

sum by (code) (
  rate(http_requests_total{
    namespace="demo",
    service="example-app"
  }[5m])
)

This query calculates requests per second, grouped by HTTP status code. Use a Time series panel to see changes in traffic and distinguish successful responses from errors.

If the panel is empty, generate requests to the sample application and allow at least two scrapes before checking again. Prometheus needs multiple counter samples to calculate a rate.

Together, these panels let you examine cluster resource consumption alongside application behavior. Save the dashboard so you can reuse it during investigations and compare the same metrics over time.

Set Up Kubernetes Alerts with PrometheusRule and Alertmanager

Dashboards help you investigate Kubernetes metrics, but alerts notify you when a condition requires attention. Prometheus evaluates alert rules against collected metrics and sends firing alerts to Alertmanager, which groups them and routes notifications to Slack, PagerDuty, or other receivers.

kube-prometheus-stack already includes alerts for common problems such as crash-looping pods, unavailable nodes, and failing scrape targets. You can inspect them using:

kubectl get prometheusrules -A

For application-specific conditions, create your own PrometheusRule.

Create a PrometheusRule for Your Application

Let’s configure an alert for the sample application deployed earlier. It has a memory limit of 256Mi per container. We’ll trigger a warning if its memory working set stays above 85% of that limit for 10 minutes.

Create a file named example-app-rules.yaml:

apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: example-app-alerts
  namespace: demo
  labels:
    release: monitoring
spec:
  groups:
    - name: example-app.rules
      rules:
        - alert: ExampleAppHighMemoryUsage
          expr: |
            sum by (namespace, pod, container) (
              container_memory_working_set_bytes{
                namespace="demo",
                container="example-app",
                metrics_path="/metrics/cadvisor"
              }
            )
            /
            sum by (namespace, pod, container) (
              kube_pod_container_resource_limits{
                namespace="demo",
                container="example-app",
                resource="memory",
                unit="byte"
              }
            ) > 0.85
          for: 10m
          labels:
            severity: warning
          annotations:
            summary: "Example application memory usage is high"
            description: "Pod {{ $labels.pod }} has used over 85% of its container memory limit for 10 minutes."

The expression divides the container’s memory working set by its configured memory limit. A value above 0.85 indicates that usage has crossed the chosen warning threshold, although it doesn’t guarantee that an OOMKill will occur.

The for: 10m condition prevents brief increases from immediately triggering notifications. The release: monitoring label allows the Prometheus instance to discover the rule.

Apply it:

kubectl apply -f example-app-rules.yaml

Open http://localhost:9090/rules to confirm that Prometheus loaded the rule. You can also check http://localhost:9090/alerts to see whether it’s inactive, pending, or firing. The rule will normally remain inactive until the sample application reaches the configured threshold.

Figure: The ExampleAppHighMemoryUsage alert rule loaded and evaluated successfully in Prometheus

Configure Slack Notifications with Alertmanager

To receive notifications, you need a Slack incoming webhook and an AlertmanagerConfig resource that tells Alertmanager where to send alerts.

First, create a Slack incoming webhook for the channel where you want to receive notifications. Save the webhook URL in a local file named slack-webhook-url.txt. Keep this file out of version control.

Store the URL in a Kubernetes Secret in the demo namespace:

kubectl create secret generic slack-webhook -n demo \
  --from-file=webhook-url=slack-webhook-url.txt

You can delete the local file after creating the Secret. The webhook remains available through the Kubernetes Secret.

Next, create slack-routing.yaml:

apiVersion: monitoring.coreos.com/v1alpha1
kind: AlertmanagerConfig
metadata:
  name: slack-routing
  namespace: demo
  labels:
    alertmanagerConfig: slack
spec:
  route:
    receiver: slack-demo
    groupBy:
      - alertname
    groupWait: 30s
  receivers:
    - name: slack-demo
      slackConfigs:
        - apiURL:
            name: slack-webhook
            key: webhook-url
          sendResolved: true

The alertmanagerConfig: slack label matches the selector configured earlier in values.yaml. Alertmanager loads this routing configuration and sends notifications through the webhook stored in the Secret.

Because this configuration belongs to the demo namespace, its route matches alerts carrying namespace: demo under the default namespace-matching behavior. The groupWait setting allows 30 seconds to collect related alerts before sending an initial notification, while sendResolved enables notifications when alerts are resolved.

Apply the configuration:

kubectl apply -f slack-routing.yaml

Check that Kubernetes created it:

kubectl get alertmanagerconfigs -n demo

Test the Alerting Workflow

You don’t need to exhaust the application’s memory to test notifications. Instead, create a temporary alert using vector(1), which always evaluates to a positive value.

Save this as test-alert.yaml:

apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: test-alert
  namespace: demo
  labels:
    release: monitoring
spec:
  groups:
    - name: alerting-test
      rules:
        - alert: TestSlackRouting
          expr: vector(1)
          for: 1m
          labels:
            severity: warning
            namespace: demo
          annotations:
            summary: "Test notification from Prometheus"

The explicit namespace: demo label ensures that the test alert matches the Slack route.

Apply the rule:

kubectl apply -f test-alert.yaml

Open the Prometheus Alerts page. TestSlackRouting should enter the Pending state before changing to Firing after the condition has remained active for one minute.

Figure: The TestSlackRouting alert in Prometheus after entering the Firing state

To check that Alertmanager receives it, forward the Alertmanager Service:

kubectl port-forward -n monitoring \
  svc/monitoring-kube-prometheus-alertmanager 9093:9093

Open http://localhost:9093 and look for TestSlackRouting. Once Alertmanager receives the firing alert and completes its grouping delay, you should also receive a message in the Slack channel associated with your webhook.

If the alert is firing in Prometheus but isn’t visible in Alertmanager, check the connection between the two components. If Alertmanager receives it but Slack doesn’t, verify the AlertmanagerConfig, webhook Secret, and Alertmanager logs.

After confirming delivery, remove the temporary rule:

kubectl delete -f test-alert.yaml

With sendResolved: true, Alertmanager can also send a notification when the test alert resolves.

Your monitoring stack can now evaluate application-specific conditions and notify you when they occur. Review the bundled Kubernetes alerts before adding more rules, so you don’t create duplicate notifications for conditions already covered.

Troubleshoot Missing Kubernetes Metrics and Scrape Targets

When Prometheus isn’t collecting an expected metric, first determine whether the target is missing or its scrape is failing. Open Status → Service discovery and Status → Target health in Prometheus. A missing target points to a discovery or configuration problem, while a target marked DOWN indicates that Prometheus discovered it but couldn’t scrape it successfully.

Check Why Prometheus Isn’t Discovering a Target

If your application doesn’t appear among the targets, check that its ServiceMonitor exists and has the correct labels:

kubectl get servicemonitor example-app -n demo --show-labels

For the installation in this guide, the ServiceMonitor needs release: monitoring so Prometheus selects it. Its spec.selector must also match the Service’s labels, not the pod labels.

Check the Service and its endpoints:

kubectl get svc example-app -n demo --show-labels

kubectl get endpointslices -n demo \
  -l kubernetes.io/service-name=example-app

The Service should have app: example-app, and its named port must match the ServiceMonitor’s endpoints.port. If no ready application endpoints are available, check that the pods are running and that the Service selector matches their labels.

If these settings are correct but the monitor is still missing, inspect the Prometheus resource’s serviceMonitorSelector and serviceMonitorNamespaceSelector to confirm that it selects the monitor and its namespace.

Investigate Failed Scrapes

If Prometheus discovered the target but reports DOWN, open it under Target health and read the last scrape error. Use that error to narrow the investigation:

ErrorWhat to Check
Connection refusedThe application may not be listening on the configured port. Check the Service port and application container.
HTTP 404The configured metrics path may be wrong. Confirm that the application exposes /metrics.
Connection timeoutCheck network connectivity and NetworkPolicies in both the application and monitoring namespaces.
HTTP 401/403 or TLS errorCheck endpoint authentication, Prometheus permissions, and TLS configuration. Configure the appropriate credentials or trusted certificates.

To verify the example application’s metrics endpoint, forward its Service:

kubectl port-forward -n demo svc/example-app 8080:8080

In another terminal, run:

curl http://localhost:8080/metrics

You should receive Prometheus-formatted metrics, including the application’s HTTP request counters. If the endpoint works through port-forwarding but Prometheus still can’t reach it, investigate the network path from the Prometheus pods, including any NetworkPolicy restrictions.

Check Prometheus Operator Errors

A monitoring resource can pass Kubernetes API validation but still be rejected during Operator reconciliation. If you applied a ServiceMonitor or PrometheusRule and Prometheus hasn’t picked up the change, check the resource’s Kubernetes events:

kubectl get events -n demo \
  --field-selector involvedObject.name=example-app \
  --sort-by=.lastTimestamp

You can also inspect the Prometheus Operator logs for reconciliation or configuration errors:

kubectl logs -n monitoring \
  deployment/monitoring-kube-prometheus-operator \
  --tail=100

Correct any rejected configuration, then return to Prometheus Target health. For the example application’s ServiceMonitor, run:

up{namespace="demo", service="example-app"}

Both replicas should return 1 once Prometheus is scraping them successfully.

Run Prometheus on Kubernetes in Production

Once Prometheus is collecting metrics and sending alerts, you need to ensure it can handle growing workloads, retain useful history, and continue monitoring when a node fails. Focus on resource usage, high availability, long-term storage, and access control.

Manage Resource Usage, Retention, and Cardinality

Prometheus memory consumption depends heavily on the number of active time series, while disk usage depends on the volume of samples collected and how long they’re retained. Each unique combination of metric name and labels creates a separate time series.

Start by checking how many active series your Prometheus instance holds:

prometheus_tsdb_head_series

Next, check the rate at which samples are being added:

sum(rate(prometheus_tsdb_head_samples_appended_total[5m]))

Monitor these values as you add workloads. If active series or sample ingestion grows rapidly, investigate which applications and metrics are responsible before increasing Prometheus resources.

You can identify high-cardinality metrics through Status → TSDB Status in Prometheus. Alternatively, use its API with the port-forward running:

curl -s 'http://localhost:9090/api/v1/status/tsdb?limit=20'

The results include the metric names with the most series and the labels with the most distinct values.

Avoid unbounded labels such as user IDs, request IDs, and full request URLs. If you’re collecting unnecessary metrics, use metricRelabelings in the relevant ServiceMonitor to drop them before ingestion. Be careful when removing labels because doing so can create duplicate series.

Use your measured ingestion rate to estimate storage requirements, then adjust the retention, retentionSize, and persistent volume settings in values.yaml. Keep the retention-size limit below the volume’s full capacity to leave room for the WAL and compaction. The Prometheus storage guide provides a capacity formula based on retention duration, sample ingestion rate, and bytes per sample.

Configure High Availability and Long-Term Storage

A single Prometheus instance becomes unavailable when its Pod or node fails. To improve availability, run multiple Prometheus replicas so another instance can continue collecting metrics and evaluating alerts.

Add these settings to the existing values.yaml, under the corresponding prometheusSpec and alertmanagerSpec sections:

prometheus:
  prometheusSpec:
    replicas: 2
    podAntiAffinity: hard

alertmanager:
  alertmanagerSpec:
    replicas: 2
    podAntiAffinity: hard

The replicas settings run two Prometheus instances and two Alertmanager instances. Hard pod anti-affinity prevents replicas of the same component from sharing a node, so you need at least two eligible nodes with sufficient capacity.

Each Prometheus replica independently scrapes the same targets and evaluates the same alert rules. Alertmanager replicas coordinate notification state to reduce duplicate notifications. Because Prometheus replicas maintain separate local databases, each needs its own persistent volume.

Apply the changes using the Helm upgrade command from the installation section, then check the workloads:

kubectl get pods -n monitoring
kubectl get pvc -n monitoring

Confirm that both Prometheus replicas and both Alertmanager replicas become ready and that their persistent volume claims are bound.

High availability doesn’t increase the number of distinct targets Prometheus can handle. If a single instance can no longer process all its targets, use Prometheus Operator sharding to distribute scraping across multiple instances. Sharded deployments also need a way to query data across shards, such as Thanos Query or a central metrics backend.

For long-term retention, you have two common approaches:

  • Remote write: Configure prometheus.prometheusSpec.remoteWrite in values.yaml to forward samples to a compatible remote metrics backend, such as Grafana Mimir or a managed Prometheus service. Use the destination URL and authentication settings provided by that backend.
  • Thanos: Configure the Thanos sidecar with object storage to retain Prometheus TSDB blocks beyond the local retention period and query them through Thanos Query.

Remote storage doesn’t replace the need to monitor local disk usage. Prometheus still uses its local TSDB and WAL, and remote-write delays can occur when the destination is unavailable.

Secure and Maintain Your Monitoring Stack

Prometheus and Alertmanager expose metrics, configuration details, and operational controls. Avoid making their interfaces publicly accessible without authentication and network restrictions.

For production access, use an internal load balancer or an Ingress protected by TLS and an authentication proxy. Grafana also needs appropriate authentication and access controls.

Within Kubernetes, restrict access to monitoring components:

  • RBAC: Limit who can create or modify ServiceMonitors, PrometheusRules, and monitoring configuration.
  • NetworkPolicies: Allow Prometheus to reach application metrics endpoints while restricting unnecessary access to those endpoints.
  • Secrets: Keep Slack webhooks, remote-write credentials, and other sensitive values in Kubernetes Secrets or your existing secrets-management system.

Finally, test Helm upgrades before applying them to production. Prometheus Operator upgrades may also require updates to its CRDs, which ordinary Helm upgrades don’t automatically handle. Check the chart’s upgrade instructions before changing versions.

Keep your values.yaml, custom monitoring resources, alert routes, and Grafana dashboards under version control. After each upgrade, verify that scrape targets are healthy, recording and alerting rules are loaded, and notifications still reach their intended receivers.

Monitor Kubernetes with groundcover

groundcover extends Kubernetes monitoring beyond the infrastructure and application metrics collected by Prometheus. Its eBPF sensor runs as a DaemonSet and collects request-level telemetry for supported applications without requiring code changes or per-service instrumentation. It also brings container logs and Kubernetes events into the same platform, helping you investigate application behavior alongside resource usage.

For example, when the ExampleAppHighMemoryUsage alert created earlier fires, you can examine the affected workload’s memory usage alongside request latency, errors, and traces. This helps you determine whether the increase coincides with changes in application traffic or downstream dependencies.

Collect Kubernetes and Application Telemetry with eBPF

You can add groundcover’s eBPF sensor to your existing cluster without removing Prometheus or changing the ServiceMonitors configured earlier. Its Kubernetes installation supports deployment through the CLI, Helm, or Argo CD. Once deployed, the sensor collects telemetry from supported application traffic at the Linux kernel level and associates it with Kubernetes workload context. This approach also enables zero-code instrumentation for EKS workloads.

The sensor complements the resource metrics already collected by node-exporter, kube-state-metrics, and cAdvisor. Instead of stopping at a dashboard showing high CPU or memory usage, you can investigate the requests, errors, and downstream dependencies associated with the affected workload.

Send Existing Prometheus Metrics to groundcover

You can use Prometheus remote write to forward metrics from the Prometheus instance installed earlier, preserving the ServiceMonitors and PodMonitors already configured for Kubernetes and application monitoring. With groundcover’s sensor installed in the same cluster, add the following configuration under the existing prometheus.prometheusSpec section of your kube-prometheus-stack values.yaml:

prometheus:
  prometheusSpec:
    remoteWrite:
      - url: http://groundcover-sensor.groundcover.svc.cluster.local:8428/api/v1/write

Keep the storage, retention, resource requests, and other settings already defined in that file. The remoteWrite configuration adds a destination for collected samples without replacing local Prometheus storage. Apply the change to your existing Helm release:

helm upgrade monitoring prometheus-community/kube-prometheus-stack \
  --namespace monitoring \
  --version 93.4.0 \
  -f values.yaml

Prometheus continues scraping its configured targets and forwards the collected samples to groundcover through the in-cluster sensor Service. This connection doesn’t require an additional ingestion key. To verify ingestion, open groundcover’s metrics explorer and query a metric already available in Prometheus, such as:

http_requests_total{namespace="demo"}

You should see metrics from the sample application deployed earlier. You can then explore those metrics alongside the application’s request traces, logs, and Kubernetes events to investigate performance problems from the same platform.

Reuse Grafana Dashboards and Manage Data with BYOC

groundcover stores metrics in VictoriaMetrics, a Prometheus-compatible backend, so you can continue using PromQL and your existing Grafana dashboards for Kubernetes monitoring. In Grafana, open Connections → Data sources, add a Prometheus data source, and configure:

  • Prometheus server URL: https://app.groundcover.com/api/prometheus
  • Custom HTTP header: authorization
  • Header value: Bearer <your API key>

Use an API key from your groundcover account, then select Save & test. Once connected, you can choose this data source in your existing Grafana panels and reuse the PromQL queries created earlier.

With groundcover’s Bring Your Own Cloud (BYOC) architecture, VictoriaMetrics stores metrics while ClickHouse stores logs, traces, and events within your cloud environment. groundcover manages the backend infrastructure, while node-based pricing avoids separate charges for each metric series or ingested gigabyte. This also changes the cost structure of Kubernetes monitoring with eBPF, allowing you to collect more telemetry without increasing usage-based ingestion charges.

FAQs

The Prometheus Operator simplifies Kubernetes monitoring by managing scrape targets, alert rules, storage, and replicas through Kubernetes custom resources. You can also run standalone Prometheus using kubernetes_sd_configs in prometheus.yml, but you’ll need to manage its configuration yourself. For the setup in this guide, the Operator is already included in kube-prometheus-stack.

Yes. You can run Prometheus in each cluster, assign a unique cluster external label, and aggregate metrics through Thanos Query, remote write to a central backend, or Prometheus federation. A single Prometheus instance can also scrape multiple clusters directly when network access and permissions allow, although per-cluster collection reduces dependence on cross-cluster connectivity.

No. Prometheus includes a query interface for running PromQL expressions and displaying graphs, while Prometheus and Alertmanager handle alert evaluation and notifications. Grafana adds persistent dashboards, visualization options, and workload filters. kube-prometheus-stack installs Grafana with preconfigured Kubernetes dashboards, so you can use it without configuring a separate installation.

Size Prometheus by active time series, not cluster node count. A rough historical estimate is 3 KB of memory per active series, while compressed samples require approximately 1–2 bytes each. At 100,000 series scraped every 30 seconds, 15 days of samples need about 4.3–8.6 GB before WAL and index overhead. Monitor actual usage and add remote write when you need longer retention or centralized metrics across clusters.

Sign up for Updates

Keep up with all things cloud-native observability.

We care about data. Check out our privacy policy.