πŸ’‘
Hey β€” It's Sandip Das πŸ‘‹

Monitoring is critical for understanding what’s happening in your Kubernetes cluster. Today, you’ll deep dive into using Prometheus for metrics collection and Grafana for visualization.

You’ll also explore how to monitor pods, nodes, apps, and system components with powerful queries and dashboards.

⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:


Prometheus and Grafana on Kubernetes: app pods, kubelet/cAdvisor, node-exporter, kube-state-metrics and the control plane are scraped by Prometheus, which stores samples in its TSDB, sends alerts to Alertmanager and serves PromQL to Grafana

Download a high-resolution copy of this diagram here for future reference.

πŸ“š Key Learnings

πŸ”Ή What is Prometheus, its components, and how it collects metrics in Kubernetes
πŸ”Ή What is Grafana and how it visualizes Prometheus metrics
πŸ”Ή Role of node-exporter, kube-state-metrics, Alertmanager
πŸ”Ή How metrics work: counters, gauges, histograms, summaries
πŸ”Ή PromQL basics: querying metrics in Prometheus
πŸ”Ή Installing Prometheus + Grafana & Setting up dashboards to monitor:

  • Pod health
  • Node resource usage
  • Application metrics
  • Cluster events

πŸ”Ή Sample Alert Manager Setup


🧠 Learn here

Prometheus

Prometheus is an open-source monitoring and alerting toolkit designed for reliability and scalability, especially in cloud-native environments like Kubernetes.

Core Components:

Prometheus components: instrumented apps, exporters, Pushgateway and service discovery feed the Prometheus server, which stores to local TSDB, sends alerts to Alertmanager and answers PromQL queries from Grafana
  • Time Series Database (TSDB): Stores data as metrics over time, identified by metric name and key-value pairs (labels).
  • Pull-Based Model: Prometheus scrapes (pulls) metrics from endpoints at specified intervals.
  • PromQL (Prometheus Query Language): A powerful query language to filter, aggregate, and analyze time-series data.
  • Exporters: Applications or agents that expose metrics in Prometheus format (e.g., node_exporter, kube-state-metrics).
  • Service Discovery: Dynamically finds targets (e.g., Kubernetes pods) to scrape metrics from.
  • Alertmanager: Handles alerting rules and routes alerts via email, Slack, PagerDuty, etc.

πŸ”„ How Prometheus Collects Metrics πŸ“Š in Kubernetes

1. Service Discovery

Prometheus integrates with the Kubernetes API to automatically discover:

  • Pods
  • Services
  • Endpoints
  • Nodes
  • Ingresses

Configuration Example:

scrape_configs:
  - job_name: 'kubernetes-pods'
    kubernetes_sd_configs:
      - role: pod
    relabel_configs:
      - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
        action: keep
        regex: true
      - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
        target_label: __metrics_path__
        regex: (.+)
      - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
        target_label: __address__
        regex: (.+):(?:\d+);(.+)
        replacement: ${1}:${2}

2. Targets Expose Metrics

Each discovered target (Pods/Services) should expose metrics at:

/metrics

via:

  • Native instrumentation (e.g., using Prometheus client libraries)
  • Exporters like:
    • node_exporter: OS-level metrics
    • kube-state-metrics: Kubernetes object state
    • blackbox_exporter: Probes endpoints over HTTP, TCP, DNS and ICMP

3. Prometheus Server Scrapes

Prometheus pulls data from the discovered targets at regular intervals and stores it in its local TSDB.

4. Storage & Query

  • Collected data is stored in Time Series Database (TSDB).
  • Queried using PromQL for dashboards (e.g., Grafana) or alerts (via Alertmanager).

πŸ“ˆ Workflow

K8s API β†’ Prometheus β†’ Discovers Targets β†’ Scrapes /metrics β†’ Stores in TSDB β†’ Queried via PromQL

Grafana

Grafana Dashboard (example from Grafana.com)

Grafana is an open-source analytics and visualization platform used to monitor and analyze metrics from various data sources in real time. It's widely used in DevOps, SRE, and observability workflows.

Core components:

Grafana components: data sources (Prometheus, Loki, SQL, CloudWatch) feed the Grafana server, which serves dashboards, alerting with contact points, and access control with LDAP/OAuth/SAML sign-in, storing settings in its database

1. Dashboards

  • Central interface to visualize data.
  • Consist of rows and panels.
  • Panels can be graphs, tables, heatmaps, stat blocks, etc.
  • Supports variables and dynamic filtering.

2. Panels

  • Building blocks of a dashboard.
  • Display data in various formats: Time series, Stat, Gauge, Bar gauge, Table, Pie chart.
  • Configurable queries, visualization settings, thresholds, and transformations.

3. Data Sources

  • Connects Grafana to metric/log/SQL stores.
  • Examples: Prometheus, InfluxDB, Loki, MySQL, PostgreSQL, Elasticsearch.
  • Query editors vary depending on the data source.

4. Alerting Engine

  • Sends alerts based on threshold breaches.
  • Can notify via email, Slack, PagerDuty, etc.
  • Supports alert rules, contact points, and notification policies.

5. Templating & Variables

  • Create dynamic dashboards with variables.
  • Variables allow filtering data across panels.
  • Types: query-based, constant, custom, interval.

6. Plugins

  • Extend Grafana's capabilities.
  • Types:
    • Data source plugins (e.g., AWS CloudWatch)
    • Panel plugins (extra visualizations, e.g., Business Charts)
    • App plugins (bundles of data sources, panels and pages, e.g., the Zabbix app)

7. Authentication & Authorization

  • Role-Based Access Control (RBAC).
  • Supports LDAP, OAuth, SAML, GitHub, Google Auth.
  • Assign permissions to users, teams, and orgs.

8. Folders & Permissions

  • Organize dashboards into folders.
  • Set access permissions at folder and dashboard levels.

9. Organizations

  • Multi-tenancy support.
  • Each org has separate dashboards, data sources, and users.

10. Grafana Backend Server

  • Written in Go.
  • Handles data source queries, alert evaluations, and API interactions.

11. Configuration Files

  • grafana.ini or environment variables.
  • Configure ports, logging, plugins, auth methods, etc.

12. Storage (Database)

  • Stores dashboards, users, settings.
  • Default: SQLite; also supports MySQL and PostgreSQL.

πŸ“Š How Grafana Visualizes Prometheus Metrics

1. Connecting Prometheus as a Data Source

  • Navigate to Connections > Data sources in Grafana UI.
  • Add Prometheus as a data source.
  • Provide Prometheus server URL (e.g., http://prometheus-service:9090).
  • Optionally configure scrape interval, time range, and custom headers.

2. Creating a Dashboard

  • Click Dashboards > New > New dashboard > Add visualization.
  • Choose Prometheus as the data source.
  • Use PromQL to query metrics (e.g., rate(http_requests_total[5m])).

3. Panel Visualization Options

  • Choose from different panel types:
    • Time series: Plot time-series data.
    • Stat: Display single value.
    • Gauge/Bar Gauge: Show thresholds.
    • Table: Show tabular metrics.
  • Customize visual options:
    • Legends, axes, thresholds, units, colors.

4. Using Variables

  • Create variables (e.g., instance, job) to dynamically filter Prometheus metrics.
  • Add dropdowns to the dashboard for interactive filtering.

Use variables in queries like:

rate(http_requests_total{job="$job"}[5m])

5. Alerting on Prometheus Metrics

  • Create alert rules under Alerting > Alert rules (or choose New alert rule from a panel menu).
  • Set conditions based on PromQL thresholds.
  • Route notifications with contact points and notification policies.

6. Advanced PromQL Usage

  • Aggregate functions: sum(), avg(), count(), max().
  • Rate, increase, histogram queries.

Example:

sum(rate(container_cpu_usage_seconds_total{container!=""}[5m])) by (pod)

7. Annotations and Events

  • Add annotations from Prometheus alert rules.
  • Highlight deploys, outages, and events on graphs.

8. Dashboards Templates and Imports

  • Use pre-built Prometheus dashboards from Grafana Labs.
  • Import dashboards using JSON ID or URL from Grafana.com.

πŸ” Role of Key Prometheus Monitoring Components here:

🧠 node-exporter

Collects host-level system metrics from Kubernetes nodes.

Metrics Collected:

  • CPU usage (node_cpu_seconds_total)
  • Memory usage (node_memory_*)
  • Disk I/O & space (node_disk_*)
  • Network stats (node_network_*)

Deployment Type: DaemonSet (one pod per node)

Use Case: Enables node resource dashboards and alerts about node-level issues like high CPU or disk usage.

πŸ“¦ kube-state-metrics

Exposes internal Kubernetes object states as Prometheus metrics.

Metrics Collected:

  • Pod status (kube_pod_status_phase)
  • Deployment/ReplicaSet status (kube_deployment_status_replicas)
  • Resource quotas, limits, and labels

Deployment Type: Deployment (single instance)

Use Case: Supports application health and scheduling-related dashboards (e.g., pod restarts, pending pods).

🚨 Alertmanager

Handles alert notifications sent by Prometheus when alert rules fire.

Key Features:

  • Grouping similar alerts
  • Routing to different receivers (email, Slack, PagerDuty, etc.)
  • Silencing and inhibition of noisy alerts

Deployment Type: StatefulSet (usually with persistent volume for state)

Use Case: Enables real-time alerting on issues like high resource usage, pod failures, or unreachable nodes.


πŸ“ How Metrics Work: Prometheus Metric Types

Prometheus supports four primary metric types, each serving a different purpose in observability. Grafana visualizes these metrics by querying them via PromQL and rendering them into meaningful dashboards.

1. Counter

  • Definition: Monotonically increasing value that only increases or resets to zero.
  • Use Case: Counting events like HTTP requests, errors, job completions.
  • Example Metric: http_requests_total
  • Grafana Usage: Useful for understanding event rates over time.

PromQL Example:

rate(http_requests_total[5m])

2. Gauge

  • Definition: Numeric value that can go up and down.
  • Use Case: CPU usage, memory usage, temperature, active sessions.
  • Example Metric: node_memory_Active_bytes
  • Grafana Usage: Best for monitoring fluctuating resources in real-time.

PromQL Example:

node_memory_Active_bytes / node_memory_MemTotal_bytes * 100

3. Histogram

  • Definition: Samples observations into configurable buckets.
  • Use Case: Measuring request durations, payload sizes, response times.
  • Metric Pattern: http_request_duration_seconds_bucket{le="0.5"}
  • Associated Metrics:
    • _bucket: Count of observations less than or equal to the bucket value
    • _count: Total observations
    • _sum: Total sum of observed values
  • Grafana Usage: Visualize latency percentiles using histogram buckets.

PromQL Example:

# 95th percentile request latency over the last 5 minutes
histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))

4. Summary

  • Definition: Similar to histogram but provides quantiles directly (like 0.5, 0.9, 0.99).
  • Use Case: Request latency, execution time tracking with quantile precision.
  • Metric Pattern: http_request_duration_seconds{quantile="0.9"}
  • Grafana Usage: Less preferred over histograms due to limited aggregation support.

PromQL Example:

http_request_duration_seconds{quantile="0.95"}

🧠 Key Takeaway

  • Counters are for totals.
  • Gauges are for current values.
  • Histograms are for distributions.
  • Summaries are for percentiles.

πŸ” PromQL Basics: Querying Metrics in Prometheus

PromQL (Prometheus Query Language) is used to select and aggregate time-series data stored in Prometheus. Grafana uses PromQL to power its dashboards.

1. Instant Vector vs Range Vector

Range Vector: Series of values over a time range.

http_requests_total[5m]    # range vector: every sample from the last 5 minutes

# functions such as rate() turn a range vector back into an instant vector
rate(http_requests_total[5m])

Instant Vector: Single point per time series at the current timestamp.

http_requests_total

2. Basic Querying

Use multiple label matchers:

http_requests_total{job="api-server", status!="500"}

Filter by labels:

node_cpu_seconds_total{mode="idle", instance="node1"}

Select all time series for a metric:

node_cpu_seconds_total

3. Functions

  • avg_over_time(), max_over_time(), sum_over_time()

increase() – total increase over range:

increase(http_requests_total[5m])

rate() – per-second average rate of increase over range:

rate(http_requests_total[1m])

4. Aggregation Operators

  • without() and by() keywords to group/un-group

sum(), avg(), min(), max(), count(), stddev(), stdvar()

sum(rate(http_requests_total[1m])) by (job)

5. Math Operations

Combining metrics:

# error ratio: the share of requests that failed
rate(errors_total[5m]) / rate(requests_total[5m])

Arithmetic operations with metrics:

node_memory_MemFree_bytes / node_memory_MemTotal_bytes * 100

6. Recording Rules

  • Precompute queries for performance and reuse.
  • Stored as new time series.

πŸ“¦ Installing Prometheus + Grafana in Kubernetes

πŸ”§ Step 1: Install kube-prometheus-stack via Helm

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 \
  --set grafana.service.type=NodePort \
  --set prometheus.service.type=NodePort

Run below to check all pods running

kubectl get pods -n monitoring

Expected Pods in monitoring namespace:

Pod name (release "monitoring")Description
prometheus-monitoring-kube-prometheus-prometheus-0Prometheus server (StatefulSet managed by the operator)
alertmanager-monitoring-kube-prometheus-alertmanager-0Alertmanager (StatefulSet managed by the operator)
monitoring-grafana-<suffix>Grafana dashboard UI
monitoring-kube-state-metrics-<suffix>Exposes Kubernetes object states as Prometheus metrics
monitoring-prometheus-node-exporter-<suffix>Node-level metrics exporter (DaemonSet, one pod per node)
monitoring-kube-prometheus-operator-<suffix>Prometheus Operator: manages the Prometheus, Alertmanager, ServiceMonitor, PodMonitor and PrometheusRule resources
prometheus-adapter-<suffix> (optional, separate chart)Serves custom metrics to the HPA; not part of kube-prometheus-stack, install prometheus-community/prometheus-adapter if you need it

πŸ“Š Setting Up Dashboards

1. Pod Health Monitoring

Metrics Tracked:

  • Pod restarts
  • Pod status (Running, Pending, Failed)
  • Container states

Grafana Dashboard Panels:

  • Pod Restart Count over Time
  • Top N Pods by Restart Count
  • Current Pod States

PromQL Examples:

kube_pod_status_phase{phase="Running"}
kube_pod_container_status_restarts_total

πŸ–₯️ 2. Node Resource Usage

Metrics Tracked:

  • CPU usage
  • Memory usage
  • Disk space
  • Network traffic

Grafana Dashboard Panels:

  • CPU Usage % per Node
  • Memory Usage per Node
  • Disk Usage per Node

PromQL Examples:

100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)
node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes

πŸš€ 3. Application Metrics (e.g. HTTP Requests)

Metrics Tracked:

  • Request count
  • Error rate
  • Latency
Ensure app exposes metrics using /metrics endpoint and is scraped by Prometheus.

PromQL Examples:

rate(http_requests_total{job="my-app"}[1m])
rate(http_requests_total{job="my-app", status=~"5.."}[1m])

Grafana Panels:

  • Request Rate
  • Error Rate
  • Latency Percentiles

πŸ“‹ 4. Cluster Events Monitoring

Metrics Tracked:

  • K8s events (e.g., scaling, scheduling failures)
  • Alerts
Kubernetes events are not Prometheus metrics, and kube-state-metrics does not export them. Ship them to Loki with Grafana Alloy (loki.source.kubernetes_events) or a tool such as kubernetes-event-exporter, then chart them in Grafana with LogQL.

PromQL and LogQL examples:

# Prometheus: alerts that are firing right now
ALERTS{alertstate="firing"}

# Loki (LogQL), when Grafana Alloy ships events with loki.source.kubernetes_events
sum by (reason) (count_over_time({job="loki.source.kubernetes_events"} |= "type=Warning" [5m]))

Grafana Panels:

  • Event Count by Type
  • Active Alerts Table

Final Dashboard JSON:

{
  "dashboard": {
    "id": null,
    "title": "Kubernetes Monitoring Dashboard",
    "timezone": "browser",
    "panels": [
      {
        "title": "Pod Health",
        "type": "stat",
        "gridPos": { "x": 0, "y": 0, "w": 6, "h": 4 },
        "targets": [
          {
            "expr": "sum(kube_pod_status_phase{phase=\"Running\"})",
            "format": "time_series",
            "interval": "",
            "refId": "A"
          }
        ],
        "fieldConfig": {
          "defaults": {
            "unit": "short",
            "color": { "mode": "thresholds" },
            "thresholds": {
              "mode": "absolute",
              "steps": [
                { "color": "red", "value": null },
                { "color": "green", "value": 1 }
              ]
            }
          },
          "overrides": []
        }
      },
      {
        "title": "Node CPU Usage",
        "type": "timeseries",
        "gridPos": { "x": 6, "y": 0, "w": 12, "h": 6 },
        "targets": [
          {
            "expr": "100 - (avg by (instance) (rate(node_cpu_seconds_total{mode=\"idle\"}[5m])) * 100)",
            "refId": "B"
          }
        ]
      },
      {
        "title": "Application HTTP Requests",
        "type": "timeseries",
        "gridPos": { "x": 0, "y": 6, "w": 12, "h": 6 },
        "targets": [
          {
            "expr": "rate(http_requests_total[5m])",
            "refId": "C"
          }
        ]
      },
      {
        "title": "Firing Alerts",
        "type": "table",
        "gridPos": { "x": 0, "y": 12, "w": 24, "h": 6 },
        "targets": [
          {
            "expr": "ALERTS{alertstate=\"firing\"}",
            "refId": "D"
          }
        ]
      }
    ],
    "schemaVersion": 30,
    "version": 1,
    "refresh": "10s"
  },
  "overwrite": true
}

πŸ›‘οΈ Notes

  • Access Grafana: kubectl port-forward svc/monitoring-grafana 3000:80 -n monitoring
  • Grafana login: user admin; get the password from the chart's secret: kubectl get secret monitoring-grafana -n monitoring -o jsonpath="{.data.admin-password}" | base64 -d
  • Import dashboards from: Grafana Dashboards
  • Use Prometheus as data source in Grafana

🚨 Setting Up Alertmanager in Kubernetes

(via kube-prometheus-stack)

Configure Alertmanager Receivers

Create a values.yaml override file:

alertmanager:
  config:
    global:
      resolve_timeout: 5m
    route:
      receiver: 'slack-notifications'
    receivers:
    - name: 'slack-notifications'
      slack_configs:
      - api_url: '<SLACK_WEBHOOK_URL>'
        channel: '#alerts'
        send_resolved: true

Apply the configuration:

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

Verify Alertmanager is Working

kubectl get pods -n monitoring | grep alertmanager

Port-forward and access the UI:

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

Open http://localhost:9093

Create Alert Rules in Prometheus

Sample rule:

apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: high-cpu-usage
  namespace: monitoring
  labels:
    release: monitoring   # kube-prometheus-stack only loads rules that carry its release label
spec:
  groups:
  - name: node.rules
    rules:
    - alert: HighCPUUsage
      expr: 100 - (avg by (instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 80
      for: 2m
      labels:
        severity: warning
      annotations:
        summary: "High CPU usage on {{ $labels.instance }}"

Apply the rule:

kubectl apply -f prometheus-rule.yaml

🧠 Final Thought:


Monitoring is your superpower in production β€” with Prometheus & Grafana, you can visualize, alert, and diagnose issues in real time. Master it to operate Kubernetes with confidence. πŸ”ŽπŸ”₯


πŸ“– Learning References

πŸ“Œ Prometheus Docs
πŸ“Œ PromQL Tutorial
πŸ“Œ Kube-Prometheus Stack GitHub
πŸ“Œ Grafana Docs
πŸ“Œ Best Grafana Dashboards
πŸ“Œ Alertmanager Docs


πŸ”₯ Challenges

πŸ’‘ Challenge 1: Install kube-prometheus-stack using Helm
πŸ’‘ Challenge 2: Access Prometheus and list all targets
πŸ’‘ Challenge 3: Access Grafana and import the Kubernetes cluster monitoring dashboard
πŸ’‘ Challenge 4: Create a dashboard panel showing CPU usage of all nodes
πŸ’‘ Challenge 5: Run a pod with high CPU usage and observe in Grafana

πŸ’‘ Challenge 6: Write a PromQL query to find:

  • Pods using most memory
  • Node CPU usage over time

πŸ’‘ Challenge 7: Enable alerting for Pod restarts and memory overuse
πŸ’‘ Challenge 8: Install and configure Alertmanager to send Slack/Email alerts
πŸ’‘ Challenge 9: Instrument a sample app with Prometheus client library (Python, Go, or Node.js)
πŸ’‘ Challenge 10: Create a custom dashboard with app + system metrics

🏁 Challenge 11: Final Project: Full Monitoring Stack for Your Kubernetes App

πŸ“Œ Deploy:

  • A demo app (e.g., NodeJS/ExpressJs, Python/Flask)
  • Prometheus + Grafana using Helm
  • Expose app metrics on /metrics using a Prometheus client
  • Create a ServiceMonitor to scrape your app (give it the label release: monitoring so the stack's Prometheus selects it)
  • Visualize app metrics on a custom Grafana dashboard

πŸ’‘Bonus: Setup alerts for crash, high memory, or latency

πŸ“Œ Push your charts, dashboards, and README.md to GitHub


🀷🏻 How to Participate?

βœ… Complete the tasks and challenges.
βœ… Document your progress and key takeaways on GitHub ReadMe, Medium, or Hashnode.
βœ… Share the above in a LinkedIn post tagging me (Sandip Das), and use #60DaysOfDevOps to engage with the community!


⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:

Share this post