Skip to content
Reviewed by Bipeen Sinha Nov 27, 2026

Home › Guides › Prometheus and Grafana tutorial

Tutorial · 2026

Prometheus and Grafana Tutorial 2026: Monitor Your First App in 8 Steps With Docker Compose

This Prometheus and Grafana tutorial takes you from an empty folder to a live dashboard in 8 steps: instrument a Python service, scrape it with Prometheus 3.16.0, query it in PromQL, chart it in Grafana, and fire one alert rule. Everything runs locally under Docker Compose on a laptop.

27 November 202611 min readBy the 360 Digital Transformation Editorial Team
Key takeaways
  • Prometheus pulls, it does not receive. Your app just exposes a text page at /metrics; Prometheus fetches it on a timer. If you understand that one sentence, the rest of the setup is configuration.
  • Four files are enough. A docker-compose.yml, a prometheus.yml, one alert rules file and one instrumented app. No agent, no database to provision.
  • Counters are useless raw. You almost never graph a counter; you graph rate() of it over a window, and that window has to be at least four scrape intervals wide.
  • Cardinality is the only thing that will actually hurt you. One label with user IDs in it can multiply your series count past what the box can hold, which is exactly how GoDaddy's Istio sidecars ate their memory.
  • Grafana is a window, not a store. Grafana OSS 13.3.1, released on 10 November 2026 under AGPLv3 per the official Grafana download page, keeps no metrics of its own.
  • Skip Alertmanager routing trees on day one. One rule that fires to one channel teaches you more than a severity matrix nobody reads.

Picture a two-person platform team at a logistics SaaS in Pune. Their API slowed to a crawl last Tuesday at 9:40 PM, customers noticed before they did, and the only evidence afterwards was a wall of application logs that said nothing about how long requests had been taking. Logs tell you what happened in one request. Metrics tell you what is happening across all of them, which is the question you actually have at 9:40 PM. That is the gap Prometheus fills. Learning how to monitor an application with Prometheus starts with building the smallest useful version of it, which is what the next two hours do.

How to Monitor an Application With Prometheus: What You Are Building

Prometheus is a pull-based time series database. It reads a plain-text endpoint on your service every few seconds, stamps each number with the time and a set of labels, and stores it locally. Grafana then queries Prometheus and draws the picture. Nothing in your application code ever talks to Grafana, and nothing pushes metrics anywhere.

That pull model has one consequence worth knowing up front: Prometheus must be able to reach your app over the network, not the other way round. Inside Docker Compose that is free, because every service resolves every other by name. On a laptop talking to a cloud workload it is the thing most likely to block you.

The scrape loop, end to end

Five moving parts, one direction of travel: everything flows left to right because Prometheus does the asking.

Prometheus scrape architecture with Grafana and Alertmanager Your Python app and node_exporter each expose a metrics endpoint. Prometheus pulls both over HTTP every 15 seconds and stores samples in its local TSDB. Grafana queries Prometheus with PromQL to draw dashboards, while Prometheus evaluates alert rules and hands firing alerts to Alertmanager, which notifies a Slack channel or phone. Your Python app :8000/metrics node_exporter :9100/metrics Prometheus :9090 scrape loop local TSDB rule evaluation Grafana :3000 dashboards only Alertmanager :9093 dedupe & route Slack or your phone GET every 15s same pull, no push PromQL query alert after for: 5m notify once

Component versions and ports as shipped in the official images, checked 27 November 2026.

The versions you should pin today

Pin these in your compose file rather than using :latest, so your lab still works next month.

3.16.0
Latest Prometheus, released 4 Nov 2026
3.13.5
The current LTS line, for anything long-lived
13.3.1
Latest Grafana OSS, released 10 Nov 2026
1.13.1
Latest node_exporter, released 19 Nov 2026

Versions and dates as listed on the official Prometheus download page, the Prometheus GitHub releases page and the Grafana download page, checked 27 November 2026.

Prometheus and Grafana Tutorial: The 8 Steps at a Glance

Budget two hours if Docker is already installed. The first five steps are mechanical, step 6 is where it starts to feel like engineering, and step 8 is the one most tutorials skip.

The build order

Do them in sequence; each step leaves something you can verify in a browser before moving on.

Step 1

Instrument the app

Add the client library and expose /metrics. Deliverable: you can curl the endpoint and see text.

Step 2

Write prometheus.yml

Two scrape jobs, one global interval. Deliverable: the file passes promtool check config.

Step 3

Bring up Docker Compose

Prometheus, Grafana, node_exporter and your app on one network. Deliverable: three UIs load.

Step 4

Confirm the targets are UP

Check the Targets page before you write a single query. Deliverable: no red rows.

Step 5

Generate traffic

Loop a few hundred requests through the app. Deliverable: counters that are not zero.

Step 6

Write real PromQL

Request rate, error ratio and a latency quantile. Deliverable: three queries you understand.

Step 7

Build the dashboard

Four panels, no more, wired to the Prometheus data source. Deliverable: one saved dashboard.

Step 8

Ship one alert rule

Error ratio above 5 percent for 5 minutes. Deliverable: an alert you have seen fire on purpose.

Timings assume Docker Desktop or Docker Engine already installed, checked 27 November 2026.

Steps 1 and 2: instrument the app, then describe it to Prometheus

Here is a complete instrumented service. Three metric types cover almost everything you will ever need: a Counter that only goes up, a Gauge that moves both ways, and a Histogram that buckets durations so you can ask for quantiles later.

# app.py  (pip install fastapi uvicorn prometheus-client)
import random, time
from fastapi import FastAPI, Response
from prometheus_client import Counter, Histogram, Gauge, generate_latest, CONTENT_TYPE_LATEST

app = FastAPI()

REQS = Counter("app_requests_total", "Total HTTP requests", ["method", "path", "status"])
LAT  = Histogram("app_request_seconds", "Request duration", ["path"])
QUEUE = Gauge("app_queue_depth", "Jobs waiting in the queue")

@app.get("/work")
def work():
    start = time.perf_counter()
    time.sleep(random.uniform(0.01, 0.4))
    status = "500" if random.random() < 0.07 else "200"
    LAT.labels(path="/work").observe(time.perf_counter() - start)
    REQS.labels(method="GET", path="/work", status=status).inc()
    QUEUE.set(random.randint(0, 25))
    return Response(status_code=int(status), content="ok")

@app.get("/metrics")
def metrics():
    return Response(generate_latest(), media_type=CONTENT_TYPE_LATEST)

Note what the labels are: method, path and status. All three have a small, fixed set of values. There is no user ID, no order ID and no raw URL in there, and that restraint is the single most important design decision in the file. More on why in the cardinality section.

Now the scrape config. Prometheus's own getting started guide uses a global scrape_interval of 15 seconds in its example configuration, which is a sensible default for a service you care about.

# prometheus.yml
global:
  scrape_interval: 15s
  evaluation_interval: 15s

rule_files:
  - /etc/prometheus/rules.yml

scrape_configs:
  - job_name: "demo-api"
    static_configs:
      - targets: ["api:8000"]

  - job_name: "node"
    static_configs:
      - targets: ["node-exporter:9100"]

  - job_name: "prometheus"
    static_configs:
      - targets: ["localhost:9090"]

Validate it before you start anything: docker run --rm -v $(pwd)/prometheus.yml:/p.yml prom/prometheus:v3.16.0 promtool check config /p.yml. A typo caught here saves twenty minutes of staring at an empty graph.

Step 3: the Prometheus Docker Compose file

# docker-compose.yml
services:
  api:
    build: .
    ports: ["8000:8000"]

  prometheus:
    image: prom/prometheus:v3.16.0
    ports: ["9090:9090"]
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml:ro
      - ./rules.yml:/etc/prometheus/rules.yml:ro
      - prom-data:/prometheus
    command:
      - "--config.file=/etc/prometheus/prometheus.yml"
      - "--storage.tsdb.retention.time=15d"
      - "--web.enable-lifecycle"

  node-exporter:
    image: prom/node-exporter:v1.13.1
    ports: ["9100:9100"]

  grafana:
    image: grafana/grafana-oss:13.3.1
    ports: ["3000:3000"]
    environment:
      - GF_SECURITY_ADMIN_PASSWORD=admin

volumes:
  prom-data:

Two flags there are worth your attention. --storage.tsdb.retention.time is how long samples live on disk, and the named volume is what stops you losing them on every restart. --web.enable-lifecycle lets you reload config with curl -X POST http://localhost:9090/-/reload instead of bouncing the container, which you will do a dozen times today.

With the Prometheus Docker Compose file saved, run docker compose up -d, then open the Targets page at localhost:9090/targets. That is step 4, and it is not optional: a target in DOWN state with a connection refused error is the most common reason a beginner's dashboard stays empty, and the Targets page names the cause in plain English. Also read: our Docker tutorial for beginners if the compose syntax above is new to you.

PromQL Examples That Earn Their Place on a Dashboard

The PromQL examples below are the four queries that end up on almost every service dashboard. Generate some traffic first: for i in $(seq 1 400); do curl -s localhost:8000/work > /dev/null; done. Now the queries. The thing nobody tells you clearly is that a raw counter is almost never interesting. app_requests_total is a number that goes up forever and resets to zero when the process restarts. What you want is its slope.

What you want to know PromQL Why it is written that way
Requests per second, last 5 minutes sum(rate(app_requests_total[5m])) rate() handles counter resets for you; sum() collapses every label combination into one line
Error ratio as a fraction sum(rate(app_requests_total{status="500"}[5m])) / sum(rate(app_requests_total[5m])) Ratios of two rates over the same window, never a ratio of raw counters
95th percentile latency histogram_quantile(0.95, sum by (le) (rate(app_request_seconds_bucket[5m]))) The le label is the bucket boundary, so it must survive the aggregation
Queue depth right now app_queue_depth Gauges are already instantaneous, so no rate()
Top 3 noisiest paths topk(3, sum by (path) (rate(app_requests_total[5m]))) by (path) keeps the one label you want and drops the rest
Is the target alive up{job="demo-api"} Prometheus writes this itself on every scrape; 0 means the scrape failed

One rule to carry away: the window inside rate() should be at least four times your scrape interval. At 15 second scrapes, [1m] gives the function four samples to work with and any gap makes the result jump around; [5m] is the safe default. Go narrower and your graph turns into noise that you will misread at 2am.

If you have ever written DAX measures or SQL window functions, PromQL will click faster than you expect, because the hard part is the same: deciding what to aggregate over. Our live data analyst programme drills that habit in SQL and Power BI, and the muscle transfers directly.

Step 7: The Grafana Dashboard Worth Looking At

In Grafana at localhost:3000, add a Prometheus data source pointing at http://prometheus:9090. Use the service name, not localhost: inside the Compose network, Grafana's localhost is Grafana's own container. That single mistake accounts for a lot of "data source is not working" frustration.

Then build four panels and stop. Request rate as a time series, error ratio as a time series with the unit set to percent (0.0 to 1.0), p95 latency as a time series, and up as a stat panel showing green or red. Four panels you read every day beat forty you scroll past.

Here is the honest caveat this guide owes you. Grafana is not a business intelligence tool, and if you try to use it as one you will be unhappy. It has no data modelling layer, its table formatting is primitive next to a BI tool, and it expects that most of what you look at is a line over time. For a revenue breakdown by region you want Power BI or Tableau. For "is the API healthy right now" there is nothing better, and the two tools are not competitors.

Step 8: One Alert Rule, Not Twenty

Alerts live in Prometheus, not Grafana, when you configure it this way. Create rules.yml:

# rules.yml
groups:
  - name: demo-api
    rules:
      - alert: HighErrorRatio
        expr: |
          sum(rate(app_requests_total{status="500"}[5m]))
            / sum(rate(app_requests_total[5m])) > 0.05
        for: 5m
        labels:
          severity: page
        annotations:
          summary: "Error ratio above 5% on demo-api"
          description: "{{ $value | humanizePercentage }} of requests are failing."

The for: 5m clause is the whole craft of alerting compressed into one line. Without it, a single bad scrape wakes you up. With it, the condition has to hold continuously for five minutes before the alert leaves the PENDING state, which filters out almost every false positive you would otherwise chase. Reload, then watch localhost:9090/alerts. Prometheus 3.16.0's changelog notes a fix so that alerts with short for durations are correctly restored after a restart, which matters more than it sounds when you are testing.

My opinion, and it is not the popular one: on day one, skip Alertmanager's routing trees, inhibition rules and silence schedules entirely. One rule, one receiver. The trade-off is that you cannot group or suppress alerts yet, and you will add Alertmanager properly the week you have more than five rules. But a severity matrix built before you have ever seen an alert fire is a document, not a defence.

What Every Prometheus and Grafana Tutorial Skips: Prometheus Cardinality

Prometheus cardinality is the one failure mode that gets teams at 3am rather than in review. Every unique combination of label values is a separate time series with its own chunk of memory and disk. Add a label with 10,000 possible values and you have not added one metric, you have added ten thousand. This multiplies rather than adds, and it is how monitoring stacks die.

The best documented version of this is GoDaddy's. In their engineering post "Chasing Runaway Memory Usage in Istio Sidecars", published in October 2022, their team traced runaway memory to Istio's host header fallback: Istio treated each distinct Host header as a potential new service identity, so roughly 25 new time series appeared for every user request. Disabling host header fallback in their Envoy filters flattened the memory curve. Istio's own release notes now record that host header fallback was disabled by default for inbound traffic, and the Istio FAQ lists disabling it as the first step for reducing metric cardinality. An attacker could otherwise mint unlimited series with arbitrary Host headers, which is noted in Istio issue 18818.

Here is the desk-level version of the warning. You will be tempted, the first time you debug something, to add a user_id or order_id label so you can find the one slow request. Do not. That is what logs and traces are for. Metrics answer "how many and how fast", and the moment you put an unbounded identifier in a label you have built an expensive, badly indexed log store that falls over at the worst possible time.

What your scrape interval actually costs

Same 10,000 series, four different intervals. Halving the interval doubles everything downstream.

60scheap, coarse
14.4Msamples/day
30scommon default
28.8Msamples/day
15sused in this guide
57.6Msamples/day
5srarely justified
172.8Msamples/day

Arithmetic, not a benchmark: 10,000 series multiplied by 86,400 divided by the interval in seconds. Checked 27 November 2026.

Three guardrails to add before anyone else uses your Prometheus
  • Watch your own series count. Graph prometheus_tsdb_head_series from day one and alert when it grows by a third in a day. It is the earliest warning you will get.
  • Cap each target. Set sample_limit in the scrape job so one misbehaving service gets its scrape rejected instead of taking the server with it.
  • Drop labels at ingestion. Use metric_relabel_configs with a labeldrop action for noisy Kubernetes labels you never query, rather than hoping nobody adds them.

Common Errors and the Fix for Each

What you see Real cause Fix
Target DOWN, "connection refused" Prometheus is resolving the wrong host, usually localhost from inside its own container Use the Compose service name and the container port, for example api:8000
Empty graph, target UP No traffic yet, so the counter has only one sample and rate() cannot compute a slope Send a few hundred requests, then widen the range to [5m]
Latency quantile returns NaN The le label was aggregated away, or the histogram has no observations in the window Always keep sum by (le) inside histogram_quantile()
Grafana says "data source not working" URL points at localhost:9090 instead of the Prometheus container Set the URL to http://prometheus:9090
Prometheus restarts, memory climbs again Cardinality, almost always a label with unbounded values Find it with the Status, then TSDB page in the UI, then drop that label
Alert never fires in testing for duration longer than your test window, so it sits in PENDING Temporarily set for: 30s, confirm, then put it back

Where This Shows Up in Real Work

Back to that Pune platform team. What they ended up running is not far off what you just built: four panels per service, two alerts, and a weekly habit of deleting the metrics nobody looked at. Monitoring maturity is mostly subtraction.

Three places this skill gets tested in a hiring process. Cloud and DevOps roles ask you to explain pull versus push and why you would pick a managed option over self-hosting, which is a DOP-C02 style question; 360DT's AWS programme practises exactly that design argument live. Data engineering interviews ask how you would know a nightly pipeline silently processed zero rows, and the answer is a gauge plus a staleness alert, which is the instinct our Microsoft Fabric data engineering course builds around DP-700 pipeline monitoring. And for anyone shipping LLM features, the same primitives now cover token spend and tool-call failure rate per route, which is the ground covered in our AI engineer course. Also read: how agent observability differs from classic APM.

If you want the managed route instead of running your own, Grafana Cloud's free plan is widely listed in 2026 pricing summaries at 10,000 active metric series, 50 GB of logs a month, 14-day retention and 3 active users, with additional metrics around $6.50 per 1,000 active series. That is enough for one small service and a home lab, and it runs out faster than people expect once a Kubernetes cluster starts reporting. Confirm the current figures on Grafana's own pricing page before you plan around them.

For the enterprise end of this work, where you are instrumenting someone else's deployment under a delivery deadline, the judgement about what to measure matters more than the tooling; that is squarely the territory of our Forward Deployed Engineer course. The full certifications overview maps which exam each of these tracks ends in. Also read: 10 Kubernetes pod errors and the fix for each, since most of your future Prometheus targets will be pods.

Live course

Go from one laptop dashboard to monitoring real cloud infrastructure

Live online·Sat–Sun, 8–11 PM IST·12 weeks·Rs 29,999

A live weekend programme that prepares you for both AWS Solutions Architect Associate (SAA-C03) and AWS DevOps Engineer Professional (DOP-C02), with hands-on projects and mentor support. You practise monitoring, alerting and automation on real cloud infrastructure rather than slides.

Explore the course
AWS Solutions Architect & DevOps Engineer Course (SAA-C03 + DOP-C02)

What I Would Do Next in Your Position

Delete the lab tonight and rebuild it tomorrow from memory. It sounds like busywork, and it is the fastest way to turn a tutorial you followed into a skill you have, because the second build shows you which parts you actually understood. Then instrument something you own, even a side project with four users, and leave it running a fortnight so you learn what a normal week looks like on a graph. Baselines are the one thing you cannot study for.

Once that is running, the next step worth paying for is the cloud and automation layer around it: managed Prometheus, infrastructure as code, and the alert routing you deliberately skipped. That is the spine of the AWS Solutions Architect and DevOps programme, whose next batch runs in January 2027, and if you would rather test the teaching before you commit, sit in on a free webinar or book a demo class first.

Frequently asked questions

Is this Prometheus and Grafana tutorial enough to monitor a production app?

It is enough to monitor one small production service honestly, which is more than most small teams have. What it is missing for anything larger is high availability for Prometheus itself, long-term storage beyond local disk retention, and Alertmanager routing so the right person gets paged. Add those in that order, when you feel the lack.

What is the difference between Prometheus and Grafana?

Prometheus collects and stores the numbers and evaluates alert rules. Grafana stores no metrics at all; it queries Prometheus and draws the result. You can run Prometheus with no Grafana and use its built-in graph page, but you cannot run Grafana as your metrics store.

Do I need Kubernetes to use Prometheus?

No. The Docker Compose setup above has no Kubernetes anywhere. Kubernetes matters because its service discovery lets Prometheus find new pods automatically instead of you listing targets by hand, which is why the two are so often taught together. Learn Prometheus first on static targets; the concepts do not change.

How do I monitor a Python app with Prometheus?

Install the prometheus-client library, declare a Counter, Gauge or Histogram at module level, update it in your request handler, and expose generate_latest() on a /metrics route, exactly as in the FastAPI example above. For Django and Flask there are middleware packages that add the common HTTP metrics for you.

What is a good scrape interval for Prometheus?

15 seconds for services you would be paged about, 30 to 60 seconds for everything else. The official getting started example uses 15s. Going below 15s multiplies your storage and memory for resolution you will almost never act on, as the samples-per-day chart above shows.

Is Grafana free to use?

Grafana OSS is free and open source: the official download page lists version 13.3.1, released 10 November 2026, under AGPLv3. Grafana Cloud is the hosted product, with a free plan commonly listed at 10,000 active metric series and 50 GB of logs a month, and paid tiers above that.

Why does my Prometheus graph show nothing even though the target is UP?

Nearly always one of two things: the metric has had no activity, so the counter sits at zero and rate() has no slope to report, or your range window is too narrow for the scrape interval. Send real traffic, then query with [5m] rather than [30s].

What is cardinality in Prometheus and why does it crash servers?

Cardinality is the number of distinct time series, and every unique label value combination creates one. Because labels multiply rather than add, a single label holding user IDs or request IDs can create hundreds of thousands of series, each consuming memory in the head block. That is the mechanism behind the Istio host header case GoDaddy documented.

About this guide. 360 Digital Transformation is an Anthropic Partner and a Microsoft Authorized Training Partner. Other certification bodies, vendors and employers named here are not affiliated with us. Tools and versions change quickly; commands and figures cited were checked on 27 November 2026.

Learn it live with 360 Digital Transformation

Turn this guide into a skill employers can see

Live weekend cohortEMI available

AWS Solutions Architect & DevOps Engineer Course (SAA-C03 + DOP-C02)

Rs. 29,999Rs. 37,499 Save 20%

Tools and platforms you work with

  • Amazon Web Services
  • Terraform
  • Docker
  • Amazon EKS
  • Jenkins
  • GitHub Actions
  • Git
  • Linux
Add bonus modules
See the syllabus and batch dates

Other live courses on this career path