Learn Kubernetes · 13/14

Observability: Seeing Inside Your Cluster

10 min read

Hello there, future Kubernetes expert! 🤓

Welcome to the control room of your cluster. So far, you've learned how to build and deploy applications, but how do you know what they're actually doing? Are they happy? Are they struggling? Are they secretly plotting to take over the world? (Probably not, but we should check anyway).

This guide is all about Observability—the art and science of seeing inside your Kubernetes cluster. Think of your cluster as a complex, high-performance car. You wouldn't drive it without a dashboard telling you your speed, engine temperature, and fuel level. Observability gives you that dashboard, and much more.

Let's pop the hood and see what's going on in there! 🚗💨


The Observability Paradigm: Logging vs. Monitoring

First things first, let's clear up two terms you'll hear all the time: Monitoring and Logging. They sound similar, but they solve different problems.

The Problem: Your e-commerce app is suddenly slow. Users are complaining that checkout is taking forever. You look at your cluster, and everything seems to be running. You're flying blind. You know that something is wrong, but you have no clue what or why.

Monitoring: The "What" 🌡️

Definition: Monitoring is the process of collecting and analyzing quantitative data from your system over time to understand its health and performance. It's all about numbers, metrics, and trends.

In simple terms, monitoring answers questions you already know you need to ask, like:

  • What is the current CPU usage of my web server pods?
  • How much memory is my database using?
  • How many HTTP 500 errors have occurred in the last hour?

A Real-World Scenario: Monitoring is like a doctor performing a routine health check-up. They measure your heart rate, blood pressure, and temperature. These are pre-defined metrics that give a high-level view of your health. A high temperature might indicate a fever, telling the doctor that you are sick.

Logging: The "Why" 📜

Definition: Logging is the practice of recording discrete, timestamped events that occur within your system. Logs are the detailed, moment-by-moment story of what your application is doing.

Logging helps you answer questions you didn't know you needed to ask until something went wrong. It provides the context behind the numbers.

  • A user's payment failed. What specific error message was generated?
  • A pod keeps crashing. What were the last things it did before it died?
  • Why did the server return an HTTP 500 error for a specific request?

A Real-World Scenario: If monitoring tells the doctor you have a fever, logging is like your personal diary from the past few days. The doctor can read it to find out why you might be sick: "Monday: Ate some questionable gas station sushi. Tuesday: Started feeling a bit queasy. Wednesday: Full-blown fever." Ah-ha! The sushi is the likely culprit.

The Takeaway:
Monitoring tells you that a pod's memory usage is spiking. Logs tell you why: an infinite loop in the code is eating up all the memory. You need both to effectively troubleshoot.

Monitoring Logging
Aggregated, numerical data (metrics) Detailed, event-based text records
Answers known questions (CPU, RAM) Helps investigate unknown issues
Shows trends over time Provides context for a specific moment
Tells you what is happening Helps you discover why it happened

Now that we understand the "what" and the "why," let's look at the tools that make this happen.


Prometheus Basics: Scraping and Storing Metrics

The Problem: Okay, so we need to collect metrics. But how? Do we write a script to SSH into every single pod and check its CPU usage? With potentially hundreds or thousands of pods, that's a recipe for a very bad day. We need an automated way to collect this data at scale.

The Solution: Enter Prometheus! 🕵️‍♂️ Prometheus is the de facto standard for monitoring in the cloud-native world. It's an open-source tool that collects and stores time-series data. Think of it as a tireless detective that goes around your cluster every few seconds, asking each component, "How are you doing?" and writing down the answer.

How Prometheus Works (The Simple Version)

Prometheus works on a pull model, which is a fancy way of saying it actively goes out and gets the data. This is called scraping.

  1. Metrics Endpoint: Your applications are configured to expose a special webpage (usually at /metrics) that just lists all their current metrics in a simple text format.
  2. Prometheus Server: The main Prometheus server has a list of these /metrics endpoints.
  3. Scraping: At regular intervals (e.g., every 15 seconds), Prometheus visits each of these endpoints, reads all the metrics, and saves them in its time-series database.

Interesting Fact: This pull-based approach was inspired by Google's internal monitoring system, Borgmon. The creators of Prometheus wanted to build something with a similar philosophy for the open-source community.

Getting Started: Installing Prometheus with Helm

The easiest and most common way to install Prometheus on Kubernetes is by using Helm, the package manager for Kubernetes. We'll use the kube-prometheus-stack chart, which is an all-in-one package that includes Prometheus, Grafana (we'll get to that!), and other useful components.

  1. Add the Helm Repository:
    This command tells Helm where to find the Prometheus charts.

    bash
    helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
    helm repo update
  2. Install the Chart:
    This command installs the entire stack into a new monitoring namespace.

    bash
    helm install prometheus prometheus-community/kube-prometheus-stack --namespace monitoring --create-namespace

    And... that's it! You now have a full-fledged, production-ready monitoring system running in your cluster. It's already pre-configured to automatically discover and scrape metrics from your Kubernetes nodes and many system components.

  3. Accessing the Prometheus UI:
    To see what Prometheus is doing, you can expose its web UI.

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

    Now, open your web browser and go to http://localhost:9090. You can start exploring the metrics it's collecting! Go to the "Status" -> "Targets" page to see everything it's already scraping.


Grafana: Visualizing Kubernetes Health and Dashboards

The Problem: Prometheus is awesome at collecting data, but its web UI is... well, functional. It's great for debugging and running queries, but trying to understand the overall health of your cluster by looking at raw numbers is like trying to appreciate a masterpiece painting by looking at one pixel at a time.

The Solution: Grafana! 🎨 Grafana is an open-source visualization tool that turns your time-series data from Prometheus into beautiful, easy-to-understand dashboards.

Analogy Time: If Prometheus is the diligent librarian who collects and stores every book (metric) in a massive, perfectly organized library, Grafana is the friendly guide who creates curated reading lists and beautiful displays, so you can easily find and understand the information you need.

Getting Started: Visualizing Your Metrics

The good news? If you installed the kube-prometheus-stack chart, Grafana is already installed and pre-configured to use Prometheus as its data source!

  1. Accessing the Grafana UI:
    First, you need the default admin password.

    bash
    kubectl get secret -n monitoring prometheus-grafana -o jsonpath="{.data.admin-password}" | base64 --decode ; echo

    Now, expose the Grafana service.

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

    Open your browser to http://localhost:3000. Log in with the username admin and the password you just retrieved.

  2. Exploring Dashboards:
    The kube-prometheus-stack comes with a set of pre-built dashboards for monitoring your cluster's health.

    • Click on the "Dashboards" icon (four squares) on the left sidebar.
    • Go to the "Browse" tab.
    • You'll find dashboards for things like "Node Exporter / Nodes", "Kubernetes / Compute Resources / Cluster", and more.

Click on one of them. Instantly, you'll see graphs for CPU usage, memory, disk space, and network I/O for your entire cluster. This is the power of visualization! You can immediately spot trends and potential problems.


Centralized Logging Concepts (Fluentd / Loki)

The Problem: Your pod just died. You kubectl logs <pod-name> to see what happened, but you get an error because the pod is gone. In Kubernetes, pods are ephemeral—they can be created and destroyed at any moment. When a pod dies, its logs die with it. This is a huge problem for debugging.

The Solution: Centralized Logging. The idea is simple: as soon as logs are created, we need to ship them off the node to a central, stable location before the pod disappears.

There are many tools for this, but we'll look at two popular approaches in the Kubernetes world.

Fluentd: The Universal Log Forwarder 📮

Definition: Fluentd is an open-source data collector that acts like a universal postal service for logs. It's incredibly powerful and flexible. It can collect logs from hundreds of sources, process them, and send them to dozens of destinations like Elasticsearch, S3, or, in our case, a central log storage system.

How it works in Kubernetes:
Fluentd is typically deployed as a DaemonSet. This ensures that one Fluentd pod runs on every single node in your cluster. This pod then watches for all the log files created by the containers on its node, processes them, and forwards them to a central storage backend.

Loki: Like Prometheus, But for Logs ✍️

Definition: Grafana Loki is a log aggregation system built by the creators of Grafana. Its design philosophy is what makes it so interesting and popular.

The Big Idea: Most logging systems (like Elasticsearch) work by indexing the entire content of every log message. This makes them very powerful for full-text search, but also very expensive in terms of storage and memory.

Loki takes a different approach. It only indexes a small set of labels for each log stream (like the pod name, namespace, etc.). The raw log message itself is compressed and stored as a chunk of text.

Fun Fact: Loki's motto is "Like Prometheus, but for logs." It's designed to be cost-effective and easy to operate. By indexing only the metadata, it dramatically reduces storage costs.

Getting Started: The Loki Stack with Helm

The Loki stack consists of:

  • Loki: The main server that stores logs and processes queries.
  • Promtail: The agent (like Fluentd) that runs on each node, collects logs, and ships them to Loki.
  • Grafana: The same Grafana we use for metrics can also be used to query and visualize logs from Loki!
  1. Add the Grafana Helm Repository:

    bash
    helm repo add grafana https://grafana.github.io/helm-charts
    helm repo update
  2. Install the Loki Stack:
    This command will install both Loki and Promtail in a new loki namespace.

    bash
    helm install loki grafana/loki-stack --namespace loki --create-namespace
  3. Configure Grafana to see Loki:
    Now we just need to tell our existing Grafana installation about our new Loki data source.

    • Port-forward to Grafana as you did before (http://localhost:3000).
    • Go to "Configuration" (gear icon) -> "Data Sources".
    • Click "Add data source" and select "Loki".
    • For the URL, enter http://loki.loki:3100. (This is the in-cluster address for the Loki service).
    • Click "Save & Test".

Now, on the Grafana "Explore" page, you can switch between your Prometheus data source (for metrics) and your new Loki data source (for logs). You can query your logs using a language called LogQL, which will feel very familiar if you've used Prometheus's PromQL.

You have now built a complete, industry-standard observability stack for your Kubernetes cluster. You can see what is happening with metrics and understand why with logs, all in one beautiful interface. Happy observing! 🔭


📚 Extra Reading & References

Challenge

You are managing a Kubernetes cluster where the kube-prometheus-stack has been installed, providing a full monitoring setup with Prometheus. A new microservice, inventory-service, has been deployed. You need to configure Prometheus to begin scraping metrics from this new service.

Create the YAML manifest for a ServiceMonitor Custom Resource that will instruct Prometheus to discover and scrape the application's metrics endpoint.

Requirements:

  1. The ServiceMonitor resource itself must be created in the monitoring namespace, where Prometheus is running.
  2. It should target services located in the production namespace.
  3. It must specifically select services that have the label app: inventory-service.
  4. The Prometheus instance discovers ServiceMonitor resources that have the label release: kube-prom-stack. Ensure your resource includes this label.
  5. The target service exposes metrics on a port named web-metrics.
  6. The metrics are available at the non-default path /actuator/prometheus.
  7. Prometheus should scrape this endpoint every 30s.

Expected result

Your YAML manifest should correctly define a ServiceMonitor resource. This configuration enables the Prometheus Operator to dynamically generate scrape configurations for the inventory-service based on the labels and namespace you specified.

Correct ServiceMonitor Manifest:

yaml
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: inventory-service-monitor
  namespace: monitoring
  labels:
    release: kube-prom-stack
spec:
  namespaceSelector:
    matchNames:
    - production
  selector:
    matchLabels:
      app: inventory-service
  endpoints:
  - port: web-metrics
    path: /actuator/prometheus
    interval: 30s

Explanation:

  • apiVersion: monitoring.coreos.com/v1: This defines the ServiceMonitor Custom Resource Definition (CRD) provided by the Prometheus Operator.
  • metadata.namespace: monitoring: The ServiceMonitor resource is typically placed in the same namespace as Prometheus itself to keep monitoring configurations organized.
  • metadata.labels.release: kube-prom-stack: This is a critical label selector. The Prometheus resource deployed by the helm chart is configured with a serviceMonitorSelector that looks for this specific label. Without it, your ServiceMonitor would be ignored.
  • spec.namespaceSelector: This tells the ServiceMonitor in which namespace(s) to look for target services. Here, it is restricted to the production namespace.
  • spec.selector.matchLabels: This filters the services within the selected namespace(s). It will only select services that have the label app: inventory-service.
  • spec.endpoints: This section defines how to scrape the selected services.
    • port: web-metrics: Specifies scraping the port named web-metrics on the target Service.
    • path: /actuator/prometheus: Sets the specific HTTP path for the metrics endpoint.
    • interval: 30s: Defines a custom scrape interval for this target, overriding any global Prometheus default.
yaml

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.