> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Demo Querying Kubernetes Metrics in Grafana

> Deploy a Prometheus and Grafana monitoring stack with kube-prometheus-stack and query Kubernetes metrics, histograms, and PromQL for dashboards and alerts

In this lesson we deploy a production-ready monitoring stack (Prometheus + Grafana) using the community kube-prometheus-stack Helm chart, then explore real Kubernetes metrics (kubelet, kube-apiserver, kube-state-metrics) and how to query them in Grafana and Prometheus. This walkthrough covers how to fetch node and control-plane metrics, deploy the stack with Helm, and build useful PromQL queries for dashboards and alerts.

## 1) Inspect kubelet metrics (via kubectl proxy)

Each kubelet exposes Prometheus-format (OpenMetrics) metrics on the node, but the endpoint is authenticated. Use `kubectl` to proxy through the API server and save a node's kubelet metrics locally:

```bash theme={null}
# Save kubelet metrics from the first node to a file (bash)
kubectl get --raw "/api/v1/nodes/$(kubectl get nodes -o jsonpath='{.items[0].metadata.name}')/proxy/metrics" \
  > /root/kubelet-example.txt
```

Kubelet metrics use Prometheus exposition format. Example histogram fragment:

```text theme={null}
# HELP rest_client_request_size_bytes [ALPHA] Request size in bytes. Broken down by verb and host
# TYPE rest_client_request_size_bytes histogram
rest_client_request_size_bytes_bucket{host="192.168.7.133:6443",verb="GET",le="64"} 36
rest_client_request_size_bytes_bucket{host="192.168.7.133:6443",verb="GET",le="+Inf"} 36
rest_client_request_size_bytes_sum{host="192.168.7.133:6443",verb="GET"} 0
rest_client_request_size_bytes_count{host="192.168.7.133:6443",verb="GET"} 36
```

Gauges are also present. For example, the kubelet exposes a gauge showing how many pods it is running:

```bash theme={null}
# Show the kubelet_working_pods metric and context
cat /root/kubelet-example.txt | grep kubelet_working_pods -B1
```

Example output:

```text theme={null}
# HELP kubelet_working_pods [ALPHA] Number of pods the kubelet is actually running, broken down by lifecycle phase, whether the pod is desired, orphaned, or runtime only...
# TYPE kubelet_working_pods gauge
kubelet_working_pods{config="desired",lifecycle="sync",static=""} 4
kubelet_working_pods{config="desired",lifecycle="sync",static="true"} 4
...
```

Note: gauges represent instantaneous values (they can increase or decrease), while counters are cumulative.

***

## 2) Inspect kube-apiserver metrics

The kube-apiserver exposes a high-cardinality, comprehensive metrics set. Fetch it using `kubectl`:

```bash theme={null}
kubectl get --raw /metrics || true
# Or if metrics are saved already:
wc -l /root/kube-apiserver-example.txt
```

Typical metrics include workqueue durations, request latency histograms, and request counters:

```text theme={null}
workqueue_work_duration_seconds_bucket{name="open_api_v3_aggregation_controller",le="+Inf"} 10947
workqueue_work_duration_seconds_sum{name="open_api_v3_aggregation_controller"} 2.523272552
workqueue_work_duration_seconds_count{name="open_api_v3_aggregation_controller"} 10947

# HELP apiserver_request_duration_seconds [STABLE] Response latency distribution in seconds...
# TYPE apiserver_request_duration_seconds histogram
apiserver_request_duration_seconds_bucket{component="",dry_run="",group="",resource="",scope="",subresource="/healthz",verb="GET",version="",le="0.005"} 1
...
apiserver_request_duration_seconds_sum{component="",...} 0.008
apiserver_request_duration_seconds_count{component="",...} 1
```

The kube-apiserver metrics file can be large (example sample: \~21600 lines), so filter and sample when exploring.

***

## 3) Prometheus metric patterns and histograms

Prometheus histogram exposition generates multiple series per logical histogram:

* `<metric>_bucket{le="..."} ...` — counts up to each bucket bound
* `<metric>_sum` — total sum of all observations
* `<metric>_count` — total observation count

Together these describe a distribution. To produce percentiles (P50, P95, P99) from histogram buckets in PromQL, use `histogram_quantile()` over an aggregated `sum by (le) ( rate(..._bucket[range]) )`.

Use the PromQL `rate()` (or `increase()`) function for counter metrics (cumulative counters). For latency percentiles from histograms use `histogram_quantile()` with an aggregated `*_bucket` time rate.

***

## 4) Deploy kube-prometheus-stack with Helm

The community kube-prometheus-stack Helm chart packages Prometheus Operator, Prometheus, Alertmanager, Grafana, kube-state-metrics, and default ServiceMonitors. Install it to get a production-oriented stack quickly.

Add the Helm repo and update:

```bash theme={null}
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update
```

Edit a `values.yaml` to control retention, scrape intervals, resources, and which ServiceMonitors to enable. Example `values.yaml` excerpt:

```yaml theme={null}
# /root/values.yaml (excerpt)
prometheus:
  prometheusSpec:
    retention: "1h"          # sandbox example; production typically 7-14d
    scrapeInterval: 30s
    evaluationInterval: 30s

kubeApiServer:
  enabled: true
  serviceMonitor:
    enabled: true
    interval: 30s
    metricRelabelings:
      - sourceLabels: [__name__]
        regex: 'apiserver_request_duration_seconds_bucket|apiserver_response_sizes_bucket|apiserver_request_total'
        action: keep
      - sourceLabels: [__name__]
        regex: 'etcd_(debugging|disk|request|server).*'
        action: drop

kubelet:
  enabled: true
  serviceMonitor:
    enabled: true
    interval: 30s
    https: true

grafana:
  enabled: true
  adminPassword: "your-admin-password"
  sidecar:
    dashboards:
      enabled: true
    datasources:
      enabled: true
      allowUiUpdates: false
```

Install the chart:

```bash theme={null}
helm upgrade --install prometheus-stack prometheus-community/kube-prometheus-stack \
  -n monitoring \
  -f /root/values.yaml --create-namespace --debug
```

Helm prints NOTES with commands to retrieve the Grafana admin password and port-forward:

```text theme={null}
# Example NOTES printed by Helm (trimmed)
kubectl --namespace monitoring get pods -l "release=prometheus-stack"
kubectl --namespace monitoring get secret prometheus-stack-grafana -o jsonpath="{.data.admin-password}" | base64 -d ; echo

# Port-forward Grafana to localhost
export POD_NAME=$(kubectl --namespace monitoring get pod -l "app.kubernetes.io/name=grafana,app.kubernetes.io/instance=prometheus-stack" -o name)
kubectl --namespace monitoring port-forward $POD_NAME 3000:3000
```

Verify pods are running:

```bash theme={null}
kubectl get pods -n monitoring
```

Example output (trimmed):

```text theme={null}
NAME                                                          READY   STATUS    RESTARTS   AGE
prometheus-prometheus-stack-kube-prom-prometheus-0            2/2     Running   0          90s
prometheus-stack-grafana-86cf754f4f-fnk4p                     2/2     Running   0          108s
prometheus-stack-kube-prom-operator-6fd9d6bf6f-x5d2x          1/1     Running   0          109s
prometheus-stack-kube-state-metrics-5cd4dcc5f-7pc8z           1/1     Running   0          109s
```

kube-prometheus-stack uses the Prometheus Operator and ServiceMonitors to dynamically discover and scrape targets, and includes many pre-built Grafana dashboards and a pre-configured Prometheus data source.

***

## 5) Query metrics in Grafana Explore / Prometheus

Open Grafana (via port-forward or your configured ingress) and use Explore (compass icon) for ad-hoc PromQL queries. Useful queries:

* Rate of API server requests (per second over 5 minutes):

```promql theme={null}
rate(apiserver_request_total[5m])
```

* Filter for successful HTTP 2xx responses (regex on `code` label):

```promql theme={null}
rate(apiserver_request_total{code=~"2.."}[5m])
```

* Aggregate rate by HTTP verb:

```promql theme={null}
sum by (verb) ( rate(apiserver_request_total{code=~"2.."}[5m]) )
```

Why `rate()`? Counters are cumulative; `rate()` returns a per-second average over the window and is appropriate for dashboards and alerts.

***

## 6) Histograms and percentiles (P50, P95, P99)

Calculate percentiles from histogram buckets with `histogram_quantile()`:

Template:

```promql theme={null}
histogram_quantile(QUANTILE, sum by (le) ( rate(<metric_name>_bucket[RANGE]) ))
```

Example — 99th percentile of API server request latency:

```promql theme={null}
histogram_quantile(0.99, sum by (le) ( rate(apiserver_request_duration_seconds_bucket[5m]) ))
```

Interpretation:

* A value of `0.05` indicates 99% of requests completed within 0.05 seconds (50 ms).
* Use `histogram_quantile(0.5, ...)` for P50 (median).
* Always aggregate buckets (`sum by (le)`) across series before applying `histogram_quantile()`.

***

## 7) Counters vs. Histograms vs. Gauges

Use this quick reference for metric types and how to query them:

| Metric Type | What it represents | How to query / use | Example metric |
| - | - | - | - |
| Counter | Monotonic, cumulative value that only increases | Use `rate()` or `increase()` over a range vector, e.g. `rate(apiserver_request_total[5m])` | `apiserver_request_total` |
| Histogram | Bucketed counts + `_sum` and `_count` to describe distributions | Use `histogram_quantile()` with `sum by (le) ( rate(..._bucket[range]) )` for percentiles | `apiserver_request_duration_seconds_bucket` |
| Gauge | Instantaneous value that can go up or down | Use direct value or `avg`/`max` over time windows as needed | `container_memory_working_set_bytes` |

***

## 8) Exercise: Top containers by memory in the monitoring namespace

List the top 5 containers by working set memory (GB) in the `monitoring` namespace:

```promql theme={null}
topk(5,
  sum by (namespace, pod, container) (
    container_memory_working_set_bytes{namespace="monitoring"}
  ) / 1e9
)
```

This returns the top `namespace/pod/container` combinations by memory (in GB). Typical top consumers in a monitoring namespace include:

* Grafana (main container)
* Grafana sidecar (dashboards/datasources)
* Prometheus server
* kube-state-metrics

Why these consume memory:

* Prometheus keeps in-memory indexes and recent time-series; more targets → higher memory.
* Grafana and sidecars load dashboards and datasources into memory.
* Sidecars may maintain caches and also consume memory.

***

## Final notes and tuning guidance

* Tune Prometheus retention, scrape intervals, and target selection to balance observability needs and resource/cost constraints.
* Use `rate()` for counters, `histogram_quantile()` for histogram percentiles, and raw values/aggregations for gauges.
* The kube-prometheus-stack Helm chart simplifies deployment and includes many pre-built dashboards and ServiceMonitors that mirror the metrics you inspected manually.

## Links and references

* [Prometheus documentation](https://prometheus.io/docs/introduction/overview/)
* [Grafana documentation](https://grafana.com/docs/)
* [kube-prometheus-stack Helm chart (prometheus-community)](https://github.com/prometheus-community/helm-charts/tree/main/charts/kube-prometheus-stack)
* [Kubernetes metrics & API docs](https://kubernetes.io/docs/concepts/cluster-administration/system-metrics/)
* [Helm documentation](https://helm.sh/docs/)

> [card] [Watch Video](https://learn.kodekloud.com/user/courses/grafana-prometheus-for-metrics-driven-observability/module/86c79392-532c-42b7-8908-18bf0a84210b/lesson/4b0c0aeb-d0ee-4143-b5e5-e1eb160036c1)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.