Prometheus and Grafana Integration in Kubernetes

Prometheus and Grafana Integration in Kubernetes

Learn how Prometheus collects numbers from every part of your cluster, how Grafana turns them into dashboards you can read at a glance, and how alerts wake the right person when something goes wrong, from first principles to production habits.

Picture a hospital ward at night. Beside every bed, a machine checks the patient’s heartbeat, temperature, and breathing every few seconds, and a central recorder keeps every reading. Above the nurses’ desk, a big screen shows all the patients at once, so a nurse can see at a glance who needs attention. And if a heartbeat becomes dangerous, an alarm sounds and the right doctor is called, not the whole hospital.

Prometheus and Grafana do exactly this for a Kubernetes cluster. Prometheus is the machine that checks the vital signs of your applications and computers and records every reading. Grafana is the big screen that draws those readings as charts. Together with an alarm system called Alertmanager, they let a team see, understand, and react to the health of their systems. This tutorial explains each piece from the ground up, shows how they connect inside Kubernetes, and gives you the patterns, dangers, and habits that real teams depend on.

1Why Kubernetes Needs Monitoring

Kubernetes moves and replaces your programs constantly. Without good measurement, you cannot tell whether the whole system is healthy or quietly failing.

A cluster that keeps changing

Kubernetes is a system that runs your applications, packaged as containers, across many computers. It starts new copies when traffic grows, restarts copies that crash, and moves them between machines during maintenance. This constant change is a great strength, but it also means that the thing you want to watch keeps moving. A program that was on one machine an hour ago may now be on another, with a different address and a different name.

In the old world, an administrator could log in to a single server and look at it. In Kubernetes, there may be hundreds of short-lived pods spread across dozens of machines. Nobody can log in to each one, and many will be gone before anyone could look. A monitoring system must therefore find things automatically, record what it sees, and let people ask questions afterwards.

What monitoring answers

Good monitoring answers a few simple questions. Is the application working right now? Is it getting slower over time? Is any machine running out of memory or disk space? Did the last release make things worse? Will we need more capacity next month? Each question is answered by numbers collected regularly and stored so they can be compared across time.

Simple Analogy

Think of driving a car. You do not open the bonnet every few minutes to check the engine. You glance at a dashboard showing speed, fuel, and temperature, and a warning light tells you when something needs attention. Monitoring gives your cluster a dashboard and warning lights, so you do not have to inspect every part by hand.

Metrics, logs, and traces

Teams usually look at their systems in three ways, sometimes called the pillars of observability. Each answers a different kind of question, and they work best together.

Pillar 1

Metrics

Numbers measured over time, such as requests per second or memory used. They are small, cheap to store, and ideal for dashboards and alerts.

Pillar 2

Logs

Lines of text describing events, such as an error message. They give rich detail about a specific moment but take more space.

Pillar 3

Traces

Records that follow a single request across many services, showing where the time was spent.

This tutorial

Focus on Metrics

Prometheus and Grafana are mainly about metrics. Companion tools handle logs and traces, and Grafana can display all three side by side.

i
Start with metrics

Metrics are usually the first pillar teams adopt. They tell you that something is wrong and roughly where, and then logs and traces help you find out exactly why.

2Prometheus and Grafana: The Core Idea

Prometheus collects and stores the numbers. Grafana draws them. Alertmanager calls for help. Each does one job well.

The idea in plain words

Prometheus is an open source monitoring system. It works by visiting a list of places on a regular schedule, reading the current numbers that each place offers, and storing them together with the time they were read. This is called scraping. Because Prometheus goes and asks, rather than waiting to be told, it is called a pull-based system.

Grafana is a separate open source program for drawing charts and dashboards. It does not collect anything itself. Instead, it connects to a data source such as Prometheus, asks it questions, and shows the answers as graphs, gauges, and tables. Alertmanager is a third program that receives warnings from Prometheus and decides who should be told and how.

flowchart LR
    A["Applications and exporters expose metrics"] -->|"scraped over HTTP"| P["Prometheus stores time series"]
    P -->|"queries with PromQL"| G["Grafana dashboards"]
    P -->|"alerts from rules"| AM["Alertmanager"]
    AM --> N["Chat, email, or paging tools"]
        
FIG 1 — The basic flow: expose, scrape, store, draw, and alert

Read the figure from left to right. Applications and helper programs called exporters offer their numbers on a web address. Prometheus scrapes those addresses and stores the results. Grafana asks Prometheus questions, using a query language called PromQL, to draw dashboards. Meanwhile, rules inside Prometheus watch for trouble and send alerts to Alertmanager, which forwards them to the right people.

Simple Analogy

Imagine a weather service. Weather stations around the country each display their current readings. A collector drives round every few minutes, writes the numbers in a big logbook, and never loses a page. A television studio uses that logbook to draw the weather map, and a warning office sends storm alerts to the areas that are affected. Prometheus is the collector and logbook, Grafana is the studio, and Alertmanager is the warning office.

Pull
Prometheus fetches metrics from targets on a schedule
3
programs in the core stack: Prometheus, Grafana, Alertmanager
Time series
every metric is stored as values over time

The vocabulary you will use

Term 1

Metric

A named measurement, such as the number of requests handled or the memory in use.

Term 2

Target

A place that Prometheus visits to collect metrics, usually a web address inside a pod.

Term 3

Scrape

One visit to a target to read its current metrics. Scrapes repeat on a schedule.

Term 4

Exporter

A helper program that translates the numbers of some other system into a form Prometheus can read.

Term 5

PromQL

The query language used to ask Prometheus questions, such as “how many requests failed in the last five minutes”.

Term 6

Dashboard

A page of charts in Grafana that shows the health of one system or service at a glance.

Term 7

Alerting Rule

A condition that Prometheus checks regularly and, when true for long enough, turns into an alert.

Term 8

Alertmanager

The program that groups, silences, and sends alerts to chat tools, email, or paging services.

“Prometheus remembers the numbers, Grafana shows them, and Alertmanager makes sure someone notices.”
i
Separate jobs, on purpose

Keeping collection, drawing, and alerting in separate programs means each can be scaled, upgraded, or replaced on its own. Many teams keep Prometheus and swap Grafana for another viewer, or keep Grafana and add several data sources.

3Kubernetes Building Blocks You Need First

The monitoring stack is built from ordinary Kubernetes objects. Knowing them makes every later chapter easier.

Block 1

Pod

The smallest unit Kubernetes runs. A pod holds one or more containers and has its own network address.

Block 2

Service

A stable name and address in front of a changing group of pods, so others can find your application.

Block 3

Label and Selector

Labels are name tags on objects, and selectors pick objects by their tags. Monitoring uses them to find what to scrape.

Block 4

Namespace

A named room in the cluster that groups objects, often used to separate teams or environments.

Block 5

DaemonSet

A workload that runs one pod on every machine, ideal for agents that must watch each machine.

Block 6

ServiceAccount and RBAC

An identity for a pod and the permission rules that decide what it may read in the cluster.

Block 7

ConfigMap and Secret

Objects that hold settings and sensitive data, such as dashboard definitions and alert passwords.

Block 8

PersistentVolume

Storage that outlives a pod. Prometheus needs it to keep its recorded numbers across restarts.

Block 9

Custom Resource Definition

A way of teaching Kubernetes a new kind of object. The monitoring stack adds several, such as monitors and rules.

Block 10

Ingress

A front door that lets people reach dashboards from outside the cluster, ideally with encryption and login.

Why labels matter so much here

In a cluster where pods come and go, Prometheus cannot keep a fixed list of addresses. Instead, it asks Kubernetes, “which pods and services exist right now?”, and then selects the ones it should scrape, using labels. The same labels are attached to the collected numbers, so that a chart can later show “requests for the checkout service in the production namespace”.

Simple Analogy

Consider a school where the caretaker does the daily safety round. Classes move rooms every term, so a fixed list of rooms would be useless. The caretaker instead reads the school’s live timetable and visits every room that has a class in it today. Labels and Kubernetes discovery are that live timetable.

Permission to look

To see the pods and services of a cluster, Prometheus itself needs permission. It runs with a ServiceAccount, and access rules grant it the right to list and watch pods, services, and machines. Without these permissions, Prometheus cannot discover anything, and its target list stays empty, which is one of the commonest beginner problems.

!
Common misconception

Many people believe Kubernetes has monitoring built in. It only provides a small live view of current usage for autoscaling and quick checks. It does not keep history, draw dashboards, or send alerts. That is what Prometheus and Grafana add.

4Prometheus Basics: Metrics, Labels, and Scraping

Before wiring things together, it helps to understand what Prometheus actually stores and how it asks for it.

What a metric looks like

A metric is a name, a value, and a set of labels. For example, a metric that counts web requests might carry labels saying which service produced it, which method was used, and what status code came back. Every different combination of labels is a separate series of values over time, called a time series. Prometheus stores each one as a list of readings, each with a timestamp.

Labels are powerful, because they let you slice the same metric many ways. You can ask for all requests, only failed requests, or only failed requests from one service. But labels also have a cost, because each new combination creates a new series that must be stored. We return to this in the design chapters.

The four kinds of metric

TypeWhat it isExampleHow you use it
CounterA number that only goes up, or resets to zero on restartTotal requests handledAsk for its rate of change over a time window
GaugeA number that goes up and downMemory in use, queue lengthRead the current value, or its average and peak
HistogramCounts of observations placed into bucketsHow long requests tookWork out percentiles such as the slowest one percent
SummarySimilar to a histogram, with percentiles computed by the applicationRequest duration percentilesRead the precomputed percentiles
Simple Analogy

A counter is like the odometer of a car, which only ever grows, so you learn how fast you are going by looking at how much it changed in an hour. A gauge is like the fuel gauge, which rises and falls, so you read it directly. A histogram is like a tally sheet that counts how many journeys took under ten minutes, under twenty minutes, and so on.

How scraping works

Each target offers its current numbers as plain text at a web address, usually a path called metrics. Prometheus visits every target on a fixed interval, commonly every fifteen to thirty seconds. Each visit returns the current value of every metric that target offers. Prometheus adds a timestamp and appends the values to its store.

Prometheus also records a special metric for every target, showing whether the last scrape succeeded. This simple “up or down” value is the most useful health check of all, because it tells you at once whether a target is reachable.

Asking questions with PromQL

PromQL is the language for querying stored series. It can select series by name and labels, compute rates from counters, add up values across many pods, and calculate percentiles from histograms. A typical question in words might be: “For each service, what is the per-second rate of failed requests over the last five minutes, as a share of all requests?” The answer is a new series that can be drawn as a line or used in an alert.

Rates, not raw counters

A raw counter only ever grows, so a chart of it is a rising line that tells you little. The useful view is the rate, meaning how quickly the counter is changing per second. Almost every request-based chart is built on a rate.

Aggregation across pods

Because pods come and go, you rarely care about one pod. Queries usually add up or average values across all pods of a service, and group them by labels such as namespace or version.

Percentiles for latency

Averages hide the slow requests that upset users. Histograms let you ask for the time within which ninety-nine percent of requests finished, which is far more honest about the user experience.

!
Averages can lie

If ninety-nine requests take a tenth of a second and one takes ten seconds, the average looks fine while one user waited a very long time. Always look at percentiles for anything a person waits on.

i
Pull has a hidden benefit

Because Prometheus does the visiting, a target that cannot be reached shows up as a failed scrape, so a dead application is noticed immediately. With a push design, a silent program might simply look quiet.

5Where Kubernetes Metrics Come From

A cluster has many layers, and each layer offers its own numbers. Knowing the main sources tells you which questions you can answer.

flowchart TD
    P["Prometheus"] --> K["kubelet and cAdvisor: container CPU and memory"]
    P --> NE["node-exporter: machine metrics"]
    P --> KS["kube-state-metrics: object state"]
    P --> AP["API server and control plane components"]
    P --> APP["Your applications, using client libraries"]
    P --> IN["Ingress controller and other add-ons"]
        
FIG 2 — The main sources of metrics that Prometheus scrapes in a cluster
Source 1

kubelet and cAdvisor

The kubelet is the agent on each machine. It includes a component that reports how much processor, memory, disk, and network each container uses.

Source 2

node-exporter

A small program run on every machine as a DaemonSet. It reports the machine’s own health: processor, memory, disks, and network cards.

Source 3

kube-state-metrics

Reads the state of Kubernetes objects and turns it into numbers: how many replicas are wanted and ready, which pods are pending or restarting.

Source 4

Control Plane Components

The API server, scheduler, controller manager, and the cluster database all publish metrics about their own workload and health.

Source 5

Your Applications

Applications use small client libraries to publish their own numbers, such as requests handled and time taken.

Source 6

Add-Ons and Exporters

Ingress controllers, databases, message brokers, and many other tools offer their own metrics, directly or through an exporter.

Two components with confusingly similar jobs

Beginners often confuse kube-state-metrics and the smaller metrics-server. They answer different questions. kube-state-metrics describes the desired and actual state of objects, for example that a deployment wants five replicas but only three are ready. It is a source of history for Prometheus. Metrics-server, in contrast, only supplies the current usage of pods and machines, to support autoscaling and quick checks. It keeps no history and offers no dashboards.

ComponentAnswers the questionKeeps history?Typical use
kubelet with cAdvisorHow much does each container use?Not by itself, Prometheus stores itResource dashboards and capacity planning
node-exporterHow healthy is each machine?Not by itself, Prometheus stores itDisk full, memory pressure, network alerts
kube-state-metricsWhat is the state of my objects?Not by itself, Prometheus stores itAlerts on stuck rollouts and crashing pods
metrics-serverWhat is the usage right now?NoAutoscaling and quick checks
Simple Analogy

Consider a building. The energy meter on each flat is like cAdvisor, showing how much each tenant uses. The caretaker’s checks of lifts and boilers are like node-exporter. The register of which flats are occupied, empty, or waiting for repairs is like kube-state-metrics. And the live display in the lobby, showing today’s total only, is like metrics-server.

!
Do not confuse usage with state

A pod can use very little memory and still be broken, for example stuck restarting. Usage numbers alone will not reveal that. Combine resource metrics with state metrics to see the whole picture.

i
Your own metrics matter most

Infrastructure metrics tell you the machines are fine. Only your own application metrics tell you whether users are being served well. Instrument your applications early, even if only with request counts and durations.

6Grafana Basics: Data Sources, Dashboards, and Variables

Grafana turns rows of numbers into pictures people can read in seconds. Understanding its main ideas helps you build dashboards that people actually use.

Data sources

Grafana holds no monitoring data itself. It connects to data sources, which are the systems that do. Prometheus is the most common one for metrics. Grafana can also connect to systems that store logs and traces, and even to ordinary databases. A single dashboard can mix panels from several data sources, which is very useful when you want metrics, logs, and traces of the same incident on one screen.

Dashboards, rows, and panels

A dashboard is a page. It is made of panels, and each panel shows the result of one query as a line chart, bar chart, gauge, table, or single number. Panels can be grouped into rows, and rows can be collapsed. A dashboard is stored as a text description, in a format called JSON, which means it can be saved, shared, and kept under version control.

Element 1

Panel

One chart, gauge, or table showing the result of a single query.

Element 2

Row

A group of panels under a heading, which can be folded away to keep a large dashboard tidy.

Element 3

Variable

A drop-down at the top of the dashboard, such as namespace or pod, that changes what every panel shows.

Element 4

Time Range

The window shown on all panels, such as the last hour or the last week, chosen from a picker.

Element 5

Annotation

A marker drawn on the charts at a moment in time, such as a release, so changes can be lined up with events.

Element 6

Explore

A free-form area for trying queries and following hunches without building a dashboard first.

Simple Analogy

A dashboard is like the instrument panel of an aircraft. Each dial answers one question, and the whole panel is arranged so the pilot can scan it in a moment. Variables are like a switch that changes the panel to show the left engine, the right engine, or both. The pilot does not need to build a new panel for each question.

Variables make one dashboard serve many

Without variables, you would need a separate dashboard for every service and every environment. With variables, one dashboard can show any namespace, any deployment, or any pod, chosen from a drop-down. The drop-down’s list is often filled automatically from the labels that Prometheus has seen, so new services appear without anyone editing the dashboard.

What to put on a dashboard

Two simple methods keep dashboards focused. The first is called the RED method and is used for services that handle requests. It asks for three things: the rate of requests, the number of errors, and the duration of requests. The second is called the USE method and is used for resources such as machines and disks. It asks for utilisation, saturation, and errors. Following these methods keeps dashboards useful and prevents endless walls of unrelated charts.

MethodUsed forQuestions it asks
REDServices that answer requestsRate of requests, number of errors, duration of requests
USEMachines, disks, and other resourcesHow busy, how backed up, how many errors
Golden signalsAny user-facing systemLatency, traffic, errors, and saturation
!
A dashboard nobody reads is clutter

Teams often build dozens of dashboards for every possible metric. Most go unused. Start with one clear overview dashboard per service, and add detail only when people ask real questions that it cannot answer.

i
Put the answer first

Place the most important panels, such as error rate and latency, at the top, and the detail below. A person on call at night should see the state of the service within a few seconds of opening the page.

7Architecture of the Integrated Stack

Now that each piece is familiar, let us see how they are placed together inside a real cluster, and why the pieces are arranged that way.

The pieces and where they live

In a typical cluster, the monitoring tools live together in their own namespace, often called monitoring. A namespace is simply a named room inside the cluster that keeps related things together and apart from everything else. Putting the monitoring tools in one room makes it easy to control who can enter and to see at a glance what belongs to monitoring.

Inside that room you will usually find a Prometheus server, one or more Alertmanager pods, a Grafana pod, a kube-state-metrics pod, and a node-exporter pod on every machine. You will also find an operator, which is a helper program that looks after Prometheus for you. We will meet the operator properly in a moment.

Collector

Prometheus server

Scrapes targets, stores time series on disk, evaluates rules, and answers queries. Usually run as a StatefulSet so its disk stays attached when it restarts.

Messenger

Alertmanager

Receives alerts from Prometheus, removes duplicates, groups related ones, and sends messages to the right people. Often run as two or three copies so it survives failures.

Painter

Grafana

Draws dashboards. It keeps its own small settings store for users and saved dashboards, and it reads numbers from Prometheus.

Reporter

node-exporter

Runs on every machine through a DaemonSet and reports the health of the machine itself, such as processor use, memory, and disk space.

Reporter

kube-state-metrics

Reads the Kubernetes API and reports what the cluster believes about its objects, such as how many replicas a Deployment wants and how many it has.

Manager

Prometheus Operator

Watches for special Kubernetes objects that describe monitoring wishes, and turns them into real Prometheus settings and running pods.

Simple Analogy

Picture a newsroom. Reporters in every neighbourhood send in facts. A desk editor collects them and keeps the archive. A graphics team draws the charts for the evening broadcast. A breaking news team decides who should be phoned when something serious happens. A newsroom manager hires and assigns staff whenever a new neighbourhood is added. In the stack, the reporters are the exporters, the desk editor is Prometheus, the graphics team is Grafana, the breaking news team is Alertmanager, and the manager is the operator.

Why an operator helps

Setting up Prometheus by hand means writing a long settings file that lists every target. In a cluster where pods appear and vanish all day, that file would be out of date within minutes. The Prometheus Operator solves this by adding new kinds of objects to Kubernetes. These new kinds are called custom resources, and they are defined by a mechanism called a custom resource definition, or CRD.

With the operator installed, you can create a ServiceMonitor object that says, “please scrape every service that carries this label.” You can create a PrometheusRule object that holds alerting rules. The operator watches for these objects, rewrites Prometheus settings automatically, and tells Prometheus to reload. You describe what you want, and the operator makes it so. This is the same declarative idea that Kubernetes itself follows.

Object kindWhat it describesPlain meaning
PrometheusA Prometheus server and how it should run“Run a collector with these settings”
AlertmanagerAn Alertmanager cluster“Run a messenger service with this many copies”
ServiceMonitorWhich services to scrape“Visit every service with this label”
PodMonitorWhich pods to scrape directly“Visit these pods, even without a service”
PrometheusRuleRecording and alerting rules“Warn me when this condition holds”
ProbeChecks of outside addresses“Test this web address from the outside”

The kube-prometheus-stack bundle

Installing all of these pieces one at a time would be slow. Most teams instead use a Helm chart named kube-prometheus-stack, which installs the operator, Prometheus, Alertmanager, Grafana, node-exporter, kube-state-metrics, a set of ready-made dashboards, and a set of ready-made alerting rules. Helm is a package manager for Kubernetes, and a chart is one package. One install gives you a working monitoring system in minutes.

i
Start with the bundle, then trim

The bundle is a fine starting point because its defaults follow common good practice. After a few weeks, review what you have. Turn off dashboards and rules that do not apply, and adjust storage and retention to match your needs.

Where the pieces should run

Monitoring must survive trouble, or it is useless exactly when needed. Many teams place the monitoring pods on machines that are less likely to be crowded, and give them priority so that Kubernetes does not evict them first when memory runs low. They also give Prometheus a persistent volume, which is a disk that keeps its data when the pod moves or restarts. Without it, every restart would erase the history.

Real-World Use Case

A small online shop runs one cluster with about thirty pods. They install the bundle into a namespace called monitoring, give Prometheus a fifty gigabyte disk, and keep two weeks of history. Within an hour they have dashboards for machines, namespaces, and pods. Later they add a ServiceMonitor for their checkout service, and a new dashboard for orders per minute appears without touching the Prometheus settings file.

8Internal Working: How Prometheus Finds Your Pods

The most surprising part of Prometheus in Kubernetes is that nobody tells it where the pods are. It finds them by asking Kubernetes itself.

Service discovery

Pods in Kubernetes come and go, and their addresses change every time. A fixed list of targets would be useless. Prometheus therefore uses a feature called service discovery. It connects to the Kubernetes API, the central source of truth for the cluster, and asks for a list of pods, services, or endpoints. It then keeps watching, so it hears about every new pod almost immediately and forgets pods that are gone.

Discovery only gives Prometheus a raw list. Which of those things should actually be scraped is decided by rules called relabeling. Relabeling looks at the labels attached to each discovered item, such as its namespace, its name, and any annotations, and decides whether to keep it, drop it, or rename its labels. This is how one Prometheus can watch hundreds of pods but only scrape the ones you care about.

sequenceDiagram
    participant Op as Operator
    participant K as Kubernetes API
    participant P as Prometheus
    participant Pod as Application pod
    Op->>K: Watch for ServiceMonitor objects
    K-->>Op: New ServiceMonitor for checkout
    Op->>P: Update scrape settings and reload
    P->>K: Ask for endpoints matching the label
    K-->>P: List of pod addresses
    loop Every scrape interval
        P->>Pod: Request the metrics page
        Pod-->>P: Current numbers as text
    end
    P->>P: Store samples with timestamps
        
FIG 3 — How a new monitoring wish becomes regular scrapes of real pods

Follow the figure from top to bottom. First, someone creates a ServiceMonitor. The operator notices, updates the Prometheus settings, and asks it to reload. Prometheus then asks the Kubernetes API which pod addresses match the label. Finally, on every scrape interval, Prometheus visits each address, reads the text of numbers, and stores them with the current time.

Simple Analogy

Think of a postal worker on a delivery round in a busy town where families move house every week. The worker does not memorise addresses. Each morning the worker collects an up-to-date list from the town office, then walks the route. Kubernetes API is the town office, and service discovery is the daily list.

What a scrape looks like

A scrape is an ordinary web request. Prometheus asks a pod for a page, usually named metrics, and the pod replies with plain text. Every line has a metric name, optional labels, and a number. Prometheus reads each line, attaches extra labels that describe where it came from, such as the namespace and pod name, and stores the result.

Prometheus also records a special metric named up for every target. Its value is one when the scrape succeeded and zero when it failed. This one number is the fastest way to learn that a target has stopped answering, and many teams alert on it.

How the storage works

Prometheus keeps recent data in memory and writes it to disk in blocks that cover two hours each. Before data reaches a block, it is first written into a log called the write-ahead log, so that a crash does not lose the last few minutes. Older blocks are later merged into larger ones and finally deleted when they pass the retention limit.

The data is compressed very well, often to just one or two bytes per sample. Even so, the number of distinct series matters more than the number of samples, because every series needs an index entry and memory while it is active. This is why cardinality, the number of different label combinations, is the main thing that makes Prometheus grow.

2 hours
typical span of one storage block
15 days
common default retention before old data is removed
1 or 0
value of the up metric for each target

How a query is answered

When Grafana sends a PromQL question, Prometheus finds all the series that match the names and labels in the question, reads their samples for the requested time range, and applies the maths, such as working out a rate per second. Results are sent back as lists of points. Because everything is time stamped, Prometheus can answer questions about any moment in the past that is still within retention.

!
Slow queries hurt everyone

A single dashboard with a heavy query, refreshed every few seconds by many viewers, can slow Prometheus enough that alerts are delayed. Keep refresh intervals sensible, avoid asking for very long time ranges on busy series, and use recording rules to precompute expensive answers.

Recording rules

A recording rule is a saved question whose answer Prometheus works out on a schedule and stores as a new metric. For example, instead of adding up thousands of series every time a dashboard opens, a rule can compute the total once a minute. The dashboard then reads one simple series. Recording rules make dashboards fast and make alert conditions easier to read.

9Alerting: From a Number to a Phone Call

Dashboards are for looking. Alerts are for when nobody is looking. Good alerting means the right person is told about the right problem at the right time, and no more.

Alerting rules

An alerting rule is a condition written in PromQL, together with a waiting time. For example, “the error rate has been above five percent for ten minutes.” Prometheus checks the rule at regular intervals. When the condition first becomes true, the alert is called pending. If it stays true for the full waiting time, the alert becomes firing and is sent to Alertmanager.

The waiting time is important. Without it, a brief blip would wake someone in the night. With it, only problems that last long enough to matter cause a message.

What Alertmanager does

Prometheus only decides that something is wrong. Alertmanager decides what to do about it. It has several jobs, each of which solves a real problem that appears once you have many alerts.

Job 1

Deduplication

If two Prometheus copies send the same alert, Alertmanager keeps only one.

Job 2

Grouping

If fifty pods fail at once, Alertmanager sends one message that lists them all, instead of fifty separate messages.

Job 3

Routing

It looks at labels such as team and severity, and sends each alert to the right receiver, such as a chat channel or a paging service.

Job 4

Silencing

During planned work, you can mute matching alerts for a set period so nobody is disturbed needlessly.

Job 5

Inhibition

If a whole machine is down, alerts for the pods on it can be suppressed, because they are only symptoms.

Job 6

Repeating

Unresolved alerts are reminded at a chosen interval, and a message is sent when the problem is fixed.

flowchart TD
    R["Alerting rule in Prometheus"] -->|"condition true"| PEND["Pending"]
    PEND -->|"still true after waiting time"| FIRE["Firing"]
    FIRE --> AM["Alertmanager"]
    AM --> DEDUP["Remove duplicates"]
    DEDUP --> GROUP["Group related alerts"]
    GROUP --> ROUTE{"Route by labels"}
    ROUTE -->|"severity critical"| PAGE["Paging service"]
    ROUTE -->|"severity warning"| CHAT["Team chat channel"]
    ROUTE -->|"team platform"| MAIL["Email"]
    PEND -->|"condition false again"| OK["Resolved"]
        
FIG 4 — The life of an alert, from rule to message

In the figure, an alert starts as pending and only becomes firing if the trouble lasts. Alertmanager then removes duplicates, groups related alerts, and uses labels to choose where each one goes. Critical problems may page a person, warnings may go to a chat channel, and some may simply become emails.

Simple Analogy

A hospital has many machines that beep. If every beep rang the doctor directly, the doctor would stop listening. Instead, a nurse station collects the beeps, notes that several come from the same ward, ignores a beep when the whole ward has lost power, and calls the right doctor for the serious ones. Alertmanager is that nurse station.

The Watchdog alert

What if the alerting system itself breaks? You would hear nothing, and silence would look like good news. To guard against this, the bundle includes a special alert named Watchdog that is always firing. It is sent to Alertmanager constantly. Some outside service is set up to expect this message and to raise the alarm if it ever stops arriving. This is a dead man’s switch, and it proves the whole alert path is alive.

Writing alerts people can act on

The best alerts describe symptoms that users feel, such as slow pages or failing requests, rather than every small cause, such as one busy processor. An alert should also say what is wrong, how bad it is, and where to look next. A link to a runbook, which is a short page of steps for handling that alert, turns a frightening midnight message into a manageable task.

i
Every alert needs an owner and an action

Before adding an alert, ask two questions. Who will act on this? What will they do? If nobody can answer, the alert is noise and should be a dashboard panel instead.

Severity levels

LevelMeaningTypical action
CriticalUsers are hurt now, or will be very soonPage a person immediately
WarningSomething is degrading but not yet harmfulSend to chat, handle in working hours
InfoUseful to know, no action neededShow on a dashboard only
Page people only for problems that users feel. Everything else can wait for the morning.

10Data Flow and Lifecycle of a Metric

Follow one number on its whole journey, from a moment inside an application to a line on a chart, and finally to deletion.

Stage by stage

1

Birth

Inside an application, a piece of code adds one to a counter each time an order is placed. The number lives in the memory of the program.

2

Exposure

The program offers its current numbers as text on a metrics page. Nothing leaves the pod yet.

3

Discovery

Prometheus learns that the pod exists, thanks to service discovery, and decides it should be scraped.

4

Scrape

On the next interval, Prometheus visits the page, reads the text, and attaches labels such as namespace, pod, and job.

5

Storage

The sample is written to the write-ahead log, then kept in memory, then flushed to a block on disk.

6

Evaluation

Recording and alerting rules read the new samples on their schedule. Recording rules produce new series. Alerting rules may start pending.

7

Display

Grafana runs queries and turns the results into lines, bars, and gauges that a person can read.

8

Retirement

When the data passes the retention limit, its block is deleted. If it was sent elsewhere by remote write, a copy may live on for longer.

Simple Analogy

Think of a school exam mark. A teacher writes a mark on a paper, which is the birth. It is entered into the school register, which is the scrape. The register is filed in a cabinet, which is storage. A report card is made from it, which is display. Years later, old registers are shredded, which is retirement.

What happens when a pod disappears

When a pod is deleted, Prometheus stops finding it in service discovery, and the scrapes stop. The old series is marked stale, which means it ends cleanly instead of showing as a flat line. The stored history for that pod remains on disk until retention removes it. This lets you investigate a pod that crashed an hour ago even though it no longer exists.

What happens when Prometheus restarts

On restart, Prometheus replays the write-ahead log to rebuild what was in memory. This can take a few minutes on a large server, and during that time scrapes may be missed. If the disk is lost, the history is lost too. This is why persistent volumes, and for important data, remote copies, matter.

!
Gaps are normal, but watch them

A missed scrape leaves a small gap in a chart. A few gaps are harmless. Long gaps mean the target or Prometheus itself is struggling and should be investigated.

Sending data elsewhere

Prometheus can forward copies of its samples to another system using a feature called remote write. The other system may be a long-term store, such as Thanos, Mimir, or a hosted service. This is how teams keep years of history without making one Prometheus server enormous, and how they combine several clusters into one view.

NeedCommon answerWhy
Keep data for months or yearsRemote write to a long-term storeLocal disks are costly to grow
One view over many clustersA central store or a query layerGrafana can then ask one place
Survive loss of one PrometheusRun two identical copiesIf one fails, the other still has data

11Dashboards as Code: Making Grafana Repeatable

Clicking around to build a dashboard is fine for learning. In production, every dashboard should live in version control, so that it survives rebuilds and can be reviewed like any other change.

Why not just click?

If a dashboard exists only in the Grafana database, it can be lost when the pod is rebuilt, changed by anyone without a record, and difficult to copy to a second cluster. Teams that rely on hand-made dashboards often discover, at the worst moment, that the one dashboard everyone loved has vanished.

Provisioning

Grafana supports provisioning, which means loading data sources and dashboards from files when it starts. In Kubernetes, these files are stored in ConfigMaps. A ConfigMap is a Kubernetes object that holds small pieces of text, like settings or files, so that pods can read them without baking them into an image.

The bundle includes a small helper container, called a sidecar, that runs beside Grafana. The sidecar watches the cluster for ConfigMaps that carry a particular label. Whenever it finds one, it copies its content into the folder where Grafana looks for dashboards, and asks Grafana to reload. To add a dashboard, you simply create a labelled ConfigMap. To remove it, you delete the ConfigMap.

flowchart LR
    GIT["Dashboard files in version control"] --> CI["Pipeline applies to cluster"]
    CI --> CM["Labelled ConfigMap"]
    CM --> SC["Sidecar watches for labels"]
    SC --> GF["Grafana loads the dashboard"]
    GF --> USER["Team sees the same dashboard everywhere"]
        
FIG 5 — Dashboards travelling from version control to the screen

The figure shows the path. Dashboard files are kept in version control. A pipeline applies them to the cluster as ConfigMaps. The sidecar sees the label and loads them into Grafana. Every cluster that runs the same pipeline ends up with the same dashboards.

Simple Analogy

Think of a restaurant chain. If each branch invents its own menu on a whiteboard, the menus drift apart and are lost when the board is wiped. If head office prints menus from one master file and sends them to every branch, all branches match, and a new branch has a menu on its first day.

Data sources as code

The same idea applies to data sources. Instead of adding Prometheus by hand in the Grafana screen, you provide a file that names it and gives its address. On startup, Grafana reads the file and connects. If the address changes, you change one file and redeploy.

Variables and reuse

Good dashboards use variables, such as namespace or pod, so that one dashboard serves every service. This reduces the number of dashboards to maintain. When you find that you are copying a dashboard and changing one name, add a variable instead.

i
Use folders and naming rules

Group dashboards into folders by team or system, and give them clear names. A search for “checkout” should lead to one obvious dashboard, not five with similar titles.

Change control for dashboards

Because dashboards are files, changes can be reviewed by a colleague before they are applied. A pull request shows exactly which panels were added or which queries were changed. If a change turns out to be a mistake, it can be reverted in seconds. Grafana can be set to prevent edits from the screen for provisioned dashboards, so that the version-controlled file remains the single source of truth.

Benefits of dashboards as code

  • Dashboards survive rebuilds
  • Every change is reviewed and recorded
  • Identical dashboards across clusters
  • Easy to roll back mistakes

Costs to expect

  • Editing files is slower than clicking
  • Teams need a habit of exporting and committing
  • Large dashboards produce noisy file changes
  • Someone must own the pipeline

12Security of the Monitoring Stack

Monitoring knows a great deal about your system, and that knowledge is valuable to attackers. Protect it as carefully as the applications it watches.

Why monitoring needs protection

Metrics reveal names of services, versions of software, numbers of users, and the layout of the cluster. Labels sometimes carry sensitive information by mistake, such as email addresses or customer identifiers. Grafana can also hold credentials for many data sources. Someone who gains access could learn how to attack you or could read private business numbers.

Simple Analogy

A security control room shows every camera in a building. If the door to that room is left open, a thief can see which corridors are empty. The room needs a lock, a list of who may enter, and a rule against writing secrets on the whiteboard.

Access to Kubernetes

Prometheus needs permission to read the Kubernetes API in order to discover pods. This is given through role-based access control, or RBAC, which is a system of roles that list exactly what an account may do. Prometheus should receive a role that can only read the object kinds it needs, never the ability to change things. The same is true of kube-state-metrics, which should have read-only rights.

Protecting the metrics pages

Every application that exposes metrics offers a page anyone on the network can read. Inside a cluster, that means any pod could read it unless you say otherwise. A NetworkPolicy is a Kubernetes rule that limits which pods may talk to which. Use it so that only Prometheus can reach the metrics pages, and only trusted users can reach Grafana and Alertmanager.

Where higher assurance is needed, metrics can also be served over encrypted connections, and Prometheus can be told to present a certificate or a token when it scrapes. Some cluster components, such as the kubelet, already require an authenticated request.

Logging in to Grafana

Grafana ships with a default administrator account, and its first password must be changed right away. Better still, connect Grafana to your company login system, using a standard such as OpenID Connect, so people sign in with their normal accounts. Then map groups to roles, so that most people can only view dashboards, some can edit them, and very few can administer the system.

RiskWhat could happenProtection
Open Grafana on the internetStrangers see business data or attack the login pagePut it behind single sign-on and a proxy
Default password keptAnyone who knows the default gets full controlChange it, or use single sign-on
Metrics pages readable by any podA compromised pod learns the layout of the clusterNetworkPolicy allowing only Prometheus
Secrets in labelsPrivate data stored on disk for weeksReview labels and drop risky ones by relabeling
Wide RBAC for PrometheusA stolen token could change the clusterRead-only roles for exactly what is needed
!
Do not expose the Prometheus screen openly

Prometheus has a web page that lets anyone run queries and, if enabled, even change settings or delete data. It has no login of its own by default. Keep it inside the cluster, or place an authenticating proxy in front.

Protecting the alert channels

Alertmanager holds secrets such as chat webhook addresses and paging keys. Store them in Kubernetes Secrets, restrict who can read those Secrets, and never put them in dashboards or in shared documents. Also make sure that alert messages do not contain private customer data, since chat channels are often widely read.

Real-World Use Case

A company found that a developer had added a label carrying each customer’s email address to a metric. Not only did this create millions of series and slow Prometheus, it also placed private data into a system that many staff could read. The fix was to remove the label, use a customer tier instead, and add a review step for any new label. The lesson was that cardinality and privacy problems often arrive together.

13Advantages, Disadvantages, and Trade-offs

No tool is perfect. Knowing where Prometheus and Grafana shine, and where they struggle, helps you decide what to build around them.

Advantages

  • Built for Kubernetes: discovers pods and services on its own.
  • Open source, widely used, and supported by a huge community.
  • PromQL is powerful for slicing numbers by labels and time.
  • Pull model makes it easy to see which targets are down.
  • Grafana works with many data sources, not only Prometheus.
  • Ready-made dashboards and rules from the community save weeks of work.
  • Alertmanager handles grouping, routing, and silences well.

Disadvantages

  • A single Prometheus is not built for long-term storage or huge scale.
  • Cardinality can grow quickly and use large amounts of memory.
  • PromQL takes time to learn, and mistakes look like correct answers.
  • Only handles numbers, not logs or traces.
  • Running it well takes care: storage, upgrades, and tuning.
  • High availability means running duplicates, which need careful handling.

The main trade-offs

Most decisions with this stack are trade-offs between detail and cost. More labels, more frequent scrapes, and longer retention all give a richer picture, but each one increases memory, disk space, and the time queries take. A good team decides deliberately how much detail each service deserves.

ChoiceBenefit of going furtherCost of going further
Shorter scrape intervalFiner detail, faster alertsMore samples, more disk and processor
More labelsRicher slicing of dataMany more series, more memory
Longer retentionCompare with last month or last yearLarger disks, slower restarts
More alertsFewer missed problemsMore noise and tired people
More dashboardsViews for every questionMore upkeep, less clarity
Simple Analogy

Think of taking photographs on a holiday. You could take one photo an hour, or one every second. The second gives a wonderful record but fills the memory card in a day and makes it painful to find the good pictures. Most people pick a sensible middle, and take extra photos only at special moments.

Comparing with other approaches

ApproachStrengthWeakness
Prometheus and Grafana, self-runFull control, no per-metric fee, huge ecosystemYou run and tune it yourself
Managed Prometheus-compatible serviceLess work, scales for youCosts money, less control
All-in-one commercial monitoringLogs, traces, and metrics together with supportCost grows with size, risk of lock-in
Only the basic metrics tool in the clusterTiny and simpleOnly current numbers, no history or alerts
i
Speak the same language either way

Many managed services accept the same metrics format and the same query language. If you learn PromQL and write your dashboards and alerts carefully, moving between self-run and managed setups later is much easier.

When this stack is a good fit

It is a strong choice for teams that run Kubernetes, want detailed numbers about services and machines, and are willing to learn a little. It is a weaker choice if you need only simple uptime checks, or if nobody has time to look after it. In those cases a managed service may cost less overall.

14Design Patterns and Anti-patterns

Patterns are ways of arranging things that many teams have found to work. Anti-patterns are habits that look sensible at first but cause pain later.

Helpful patterns

Pattern 1

Monitoring as configuration

Keep ServiceMonitors, rules, dashboards, and alert routes in version control. Every change is reviewed and repeatable.

Pattern 2

Monitor next to the app

Ship a ServiceMonitor and a dashboard together with each application, so that monitoring arrives with the service and is owned by the same team.

Pattern 3

Recording rules for heavy questions

Precompute expensive totals and ratios so dashboards and alerts stay fast.

Pattern 4

Symptom-based alerts

Alert on what users feel, such as errors and slowness, and keep cause-level details on dashboards for investigation.

Pattern 5

Pairs of Prometheus servers

Run two identical Prometheus copies that scrape the same targets, so one can fail without losing alerts.

Pattern 6

Central long-term store

Let each cluster keep a short history and forward copies to a shared store that keeps months and answers cross-cluster questions.

Simple Analogy

A well-run building has a fire alarm installed by the builders when each floor is finished, not added years later by someone who never saw the plans. Shipping monitoring together with each application follows the same idea.

Anti-patterns to avoid

ANTI-PATTERN-01 Avoid
Problem

Putting high-variety values, such as user identifiers, request paths with ids, or full email addresses, into labels.

Why It’s Harmful

Every new value creates a new series. Memory climbs, queries slow down, and Prometheus may crash. Private data may also be stored by accident.

Correct Approach

Use labels with a small, known set of values, such as status class, method, or tier. Put detailed identifiers in logs or traces instead.

ANTI-PATTERN-02 Avoid
Problem

Alerting on every possible cause, such as each high processor reading, with no thought about who acts on it.

Why It’s Harmful

People receive dozens of messages, learn to ignore them, and miss the one that matters. This is often called alert fatigue.

Correct Approach

Alert on symptoms that users feel, require a waiting time, attach a runbook, and delete any alert that nobody acts on.

ANTI-PATTERN-03 Avoid
Problem

Running Prometheus without a persistent disk and with a single copy, and treating it as if it could never be lost.

Why It’s Harmful

A restart erases the history, and a failure leaves the cluster with no alerts at all, at the moment they are most needed.

Correct Approach

Give Prometheus a persistent volume, run a pair of copies for important clusters, and send data to a remote store when history matters.

ANTI-PATTERN-04 Avoid
Problem

Building all dashboards by hand in the Grafana screen and never saving them anywhere else.

Why It’s Harmful

A rebuild, a deleted volume, or an accidental change can remove them for good, and nobody knows who changed what.

Correct Approach

Provision dashboards from version-controlled files and mark them as read-only in the screen.

ANTI-PATTERN-05 Avoid
Problem

Using one huge Prometheus to scrape everything in a very large organisation, including many clusters.

Why It’s Harmful

It becomes a single point of failure, needs enormous memory, and becomes slow for every team at the same time.

Correct Approach

Use one Prometheus per cluster or per group of services, and combine them with a long-term store or a query layer.

15Best Practices and Common Mistakes

A short list of habits that keep the stack healthy, and the mistakes that most often cause trouble.

Best practices

1

Start with the bundle

Install a well-known bundle such as kube-prometheus-stack. Its defaults, dashboards, and rules give you a solid base on day one.

2

Give Prometheus a proper home

Use a persistent volume, set resource requests and limits, and choose a retention time that fits the disk size, with a size limit as a safety net.

3

Follow a naming and labelling guide

Agree on metric names, units, and label names. Consistent names make dashboards reusable and queries easy to guess.

4

Watch cardinality

Track the number of active series, review new labels, and set limits on how many samples a single target may send.

5

Alert on symptoms with runbooks

Start with error rate, latency, saturation, and availability. Attach a short runbook and an owner to every alert.

6

Test your alerts

Practise by causing a harmless failure in a test environment, and check that the right person receives the right message.

7

Version everything

Keep monitors, rules, dashboards, and routing in version control, and apply them through a pipeline.

8

Secure and back up

Use single sign-on, network rules, and read-only permissions, and keep copies of important data and settings.

Simple Analogy

Keeping a garden healthy is not one big effort but a set of small regular habits: watering, weeding, and trimming. Monitoring is the same. A little care each week keeps it useful, while a year of neglect leaves a tangle that takes months to clear.

Common mistakes

MistakeWhat goes wrongBetter habit
Never checking that targets are upA silent target looks like a healthy oneAlert on the up metric and review the targets page
Forgetting to set retentionThe disk fills and Prometheus stopsSet time and size limits and alert on disk use
Averaging latencySlow requests are hidden by fast onesUse percentiles from histograms
Using a counter without a rateThe chart only climbs and tells nothingAsk for the rate over a time window
Very short rate windowsCharts jump around or show nothingUse a window at least four times the scrape interval
Ignoring the monitoring stack itselfNobody notices when it breaksMonitor Prometheus, and keep a Watchdog alert
Copying dashboards without understanding themPanels show wrong or empty dataCheck each query against your own labels
!
Do not trust a chart just because it looks nice

Wrong units, wrong labels, or a missing rate can produce a smooth, confident line that means nothing. When you build or import a dashboard, compare it with something you already know to be true, such as a known traffic spike.

A gentle start plan

If your team is new to all this, begin in three steps. First, install the bundle and look at the ready-made dashboards for nodes and pods. Second, add monitors for your most important service and build one overview dashboard for it. Third, add just two or three alerts about user-facing symptoms, with clear owners. Grow from there only when real questions demand it.

16Monitoring the Monitor: Scaling and Troubleshooting

Prometheus exports metrics about itself. Use them, because a monitoring system that fails quietly is worse than none at all.

Numbers to watch about Prometheus

Prometheus offers detailed numbers about its own work. A few of them tell you most of what you need to know. Watch how many series are active, how fast samples are arriving, how long scrapes and rule checks take, how full the disk is, and how much memory the process uses.

Series
number of active series; the main driver of memory
Ingest
samples arriving each second
Duration
time taken by scrapes and rule checks
Disk
space used by blocks and the write-ahead log
Simple Analogy

A doctor checks their own health too. A librarian who cannot find their own books is not much use. Prometheus being able to report its own memory, disk, and speed is like the librarian keeping the library catalogue in order first.

Alerts for the stack itself

The bundle already includes rules for common problems. They warn when Prometheus cannot reach a target, when it fails to send alerts, when its disk will fill soon, when a rule takes too long, and when the number of series jumps suddenly. Read those rules once so you know what they cover, and add your own for anything unique to your setup.

Logging

Prometheus, Alertmanager, and Grafana all write logs to their standard output, which Kubernetes collects. Send those logs to your normal log system. When something goes wrong, such as a rule failing to load or a data source refusing a connection, the log will usually state the reason in plain words.

When Prometheus grows too big

Signs of trouble include restarts because of memory, very slow dashboards, and gaps in the charts. There are several remedies, and you should choose the gentlest one that works.

1

Find the noisy metrics

Ask which metrics own the most series, and remove or trim the worst ones. Very often this alone solves the problem.

2

Drop what you do not use

Use relabeling to discard metrics and labels that no dashboard or alert reads.

3

Add resources

Give Prometheus more memory and faster disks. This is simple and often enough for moderate growth.

4

Split the work

Use separate Prometheus servers for different teams or groups of services, so no single server carries everything.

5

Add a long-term store

Send data to a system built for scale and long history, and shorten local retention.

Troubleshooting the usual suspects

SymptomLikely causeWhere to look
New service does not appear on the targets pageThe label on the monitor does not match the service, or the operator does not select that namespaceCompare labels and selectors on both sides
Target is listed but downWrong port name, network rule blocking access, or the pod is not readyError message on the targets page and network rules
Dashboard panel says no dataWrong data source, wrong label names, or a time range with no samplesRun the same query directly in Prometheus
Alert never firesRule has an error, the condition is not met, or the rule was not picked upRules page and the pending state of the alert
Alert fires but no message arrivesRouting does not match, or the receiver secret is wrongAlertmanager status page and its logs
Prometheus restarts oftenOut of memory from too many seriesSeries count and pod memory limits
i
Trace the path step by step

When a number does not appear, follow its journey: is the app exposing it, is the target discovered, is the scrape succeeding, is the series stored, and is the dashboard asking the right question? Checking each step in turn finds the problem faster than guessing.

17Real-World Examples

Three short stories show how the ideas in this book work in practice. The details are typical rather than taken from any one company.

Example 1: A small team gets its first monitoring

Real-World Use Case

A team of six runs a booking website on a small cluster. Until now, they learned about problems from customer emails. They install the kube-prometheus-stack bundle, and on the first day they see that one node is nearly out of memory, which explains occasional slow pages. They add a ServiceMonitor for the booking service, build a dashboard with request rate, error rate, and slowest requests, and set two alerts: high error rate for ten minutes, and a pod restarting repeatedly. Within a month, they catch two problems before any customer notices.

Example 2: Finding a slow leak

Real-World Use Case

Every few days a payments service restarts, and nobody knows why. The team opens the memory chart for that pod over two weeks, made possible by keeping a longer retention. The line climbs steadily like a staircase until the limit, then drops. This is the classic sign of a memory leak. Comparing the release dates with the shape of the chart, they see that the slope began after one particular release. They roll it back, fix the leak, and add an alert that warns when memory will reach its limit within four hours.

Example 3: Many clusters, one view

Real-World Use Case

A company runs eight clusters in different regions. Each has its own Prometheus pair with three days of history. Each pair also forwards data to a central long-term store that keeps a year. One Grafana connects to the central store, and a variable at the top of each dashboard lets a person pick a cluster or view all of them together. When a region has trouble, the team compares it with the others in one glance. Dashboards and rules are kept in version control and applied to every cluster the same way.

Simple Analogy

The three stories are like three sizes of shop. A corner shop needs a simple till and a clear window. A busy shop needs shelves that show what is selling. A chain needs a head office that can see every branch. The stack is the same tools at different scales, and you grow it only when you need to.

What the examples share

In every story, the team began small, focused on symptoms that mattered to users, and kept history long enough to answer real questions. They treated dashboards and alerts as things that need care, not one-time setup. None of them tried to measure everything on the first day.

Start small, measure what users feel, and grow only when a real question demands it.

18Frequently Asked Questions

Short answers to questions that beginners often ask.

Q1Do I need both Prometheus and Grafana?

Prometheus alone can store data and show simple graphs, but its screen is basic. Grafana gives you much better dashboards and can combine several data sources. Most teams use both.

Q2Why does Prometheus pull instead of waiting for pushes?

Pulling lets Prometheus know at once when a target is unreachable, keeps control of the scrape schedule in one place, and makes it easy to view a target’s metrics page by hand. For short jobs that end before a scrape, a helper called the Pushgateway exists, but it should be used sparingly.

Q3What is the difference between metrics-server and Prometheus?

Metrics-server only keeps the latest processor and memory numbers so that features like autoscaling and the top command work. It does not store history or offer queries. Prometheus stores history, supports queries, and drives alerts. Many clusters run both.

Q4What does cardinality mean, and why is everyone worried about it?

Cardinality is the number of distinct series a metric produces, which depends on the combinations of label values. Each series uses memory and disk. If a label can take millions of values, the number of series explodes and Prometheus can fail.

Q5What is the difference between a ServiceMonitor and a PodMonitor?

A ServiceMonitor finds targets through Kubernetes services and their endpoints. A PodMonitor finds pods directly, which is useful when pods have no service. Both tell Prometheus what to scrape without editing its main settings.

Q6How long should I keep data?

It depends on your questions. Two weeks is enough for most day-to-day investigation. If you compare with last month or last year, or need capacity planning, send data to a long-term store rather than making local disks huge.

Q7How do I make Prometheus highly available?

Run two identical copies that scrape the same targets and send alerts to the same Alertmanager cluster. Alertmanager removes the duplicates. Note that each copy holds its own data, so a query may see slightly different values from each.

Q8Can Prometheus monitor things outside Kubernetes?

Yes. It can scrape any machine or service that exposes metrics, and exporters exist for databases, message queues, network gear, and more. Prometheus does not have to live in the same place as its targets, as long as it can reach them.

Q9What about logs and traces?

Prometheus handles numbers only. Logs and traces need other tools. Grafana can show all three side by side, which lets you jump from a spike on a chart to the related logs and traces.

Q10Why does my counter chart only go up?

Because that is what a counter does: it only increases, apart from resets when a program restarts. To see how fast it is changing, ask for its rate over a time window. That gives requests per second, errors per second, and so on.

Q11Is it safe to use imported community dashboards?

They are a great starting point, but check them first. Confirm the queries match your label names, remove panels you do not need, and review any links or plugins. Treat them as drafts that you then own.

Q12Should I alert on processor use?

Usually not by itself. High processor use is often perfectly fine. Alert on effects users feel, such as slow responses or errors. Use processor use as supporting evidence on a dashboard, or alert only when it stays extremely high for a long time and threatens to cause harm.

19Summary and Key Takeaways

A last look at the whole picture, in plain words.

A cluster with no monitoring is like a hospital ward with no charts, no monitors, and no nurse station. Things may go well for a while, but when they do not, nobody knows until it is too late. Prometheus, Grafana, and Alertmanager together give the cluster a memory, a face, and a voice: Prometheus remembers the numbers, Grafana shows them, and Alertmanager speaks up when something is wrong.

Prometheus finds pods by asking Kubernetes, scrapes their metrics pages on a schedule, and stores each number with a time. The operator turns simple Kubernetes objects into real settings, so monitoring can be described as configuration and kept in version control. Recording rules make heavy questions fast, alerting rules watch for trouble, and Alertmanager makes sure the right people hear about it, and only once.

Grafana turns those numbers into pictures. Dashboards built around clear methods, and stored as files, let a whole team see the same truth. Security matters at every step: read-only permissions, network rules, single sign-on, and care with labels. Finally, the stack must watch itself, because a quiet monitor may be a broken one.

Key Takeaways

  • Prometheus pulls, stores, and evaluates — it scrapes targets on a schedule, keeps time series on disk, answers PromQL questions, and checks rules.
  • Grafana draws and Alertmanager speaks — each does one job, and together they turn raw numbers into pictures and messages people can act on.
  • The operator makes monitoring declarative — ServiceMonitors, PodMonitors, and PrometheusRules describe what you want, and the operator makes it real.
  • Watch cardinality and labels — a few well-chosen labels are powerful, while high-variety labels break performance and can leak private data.
  • Alert on symptoms, with owners and runbooks — page people only for problems users feel, and keep everything else on dashboards.
  • Keep everything as code — dashboards, rules, and routes belong in version control, applied through a pipeline, so they survive rebuilds and can be reviewed.
  • Protect and monitor the monitor — use read-only access, network rules, and single sign-on, keep a Watchdog alert, and grow to long-term storage only when real needs appear.