Monitoring with Prometheus and Grafana / Start Here

Run, inspect and reset the practice stack

Lesson 3 of 35. Open to read. No account needed.

In this lesson you create your practice folder, start four containers with Docker Compose, and prove from their own answers that each one works. You also learn the three ways to stop the stack and exactly what each one keeps or deletes, because every later lesson assumes you can pause, resume and, when needed, reset this stack safely.

By the end you will have Prometheus collecting metrics from the shop, Grafana running and signed in, and a check script that reports seven passes.

What You Are Building

The starter practice stack. On your computer, a browser and terminal reach three containers through ports published on 127.0.0.1: 19090 to prometheus, 19200 to the shop and 19300 to grafana. Inside the Docker network pmg_default for Compose project pmg, the loadgen container sends about five requests per second to the shop, prometheus scrapes the shop's /metrics every 15 seconds and also scrapes itself, and prometheus stores samples in the volume pmg_prometheus-data. Grafana keeps its own state in pmg_grafana-data and will query Prometheus once it is connected in a later module, shown as a dashed arrow. A dashed arrow from the practice folder shows the prometheus/ folder mounted read-only into the prometheus container.

Read the diagram from the left. Your browser and terminal sit on your computer. They cannot see inside Docker's private network directly; they reach a container only through a published port, a port on your computer that Docker forwards to a port inside one container. The stack publishes three, all on 127.0.0.1, so nothing on your network can reach them:

On your computerForwards toUsed for
127.0.0.1:19090prometheus, port 9090Prometheus web pages and HTTP API
127.0.0.1:19200shop, port 8000The practice service and its /metrics page
127.0.0.1:19300grafana, port 3000Grafana's web interface

Inside the network, containers find each other by service name: the load generator sends requests to http://shop:8000, and Prometheus collects metrics from shop:8000. The load generator has no published port because nothing outside needs to reach it.

Two named volumes hold data that must survive the containers being replaced: Prometheus's stored samples and Grafana's own settings and users. A container can be deleted and recreated; the volume stays until you delete it on purpose.

Before You Start

You need Docker with Compose version 2, a terminal, a text editor and about 4 GB of free disk space. Check them now, in any folder:

docker version --format 'client {{.Client.Version}}, server {{.Server.Version}}'
docker compose version

Both commands must print versions. If the first one prints a client version and then an error about connecting to the Docker daemon, Docker Desktop (or the Docker service on Linux) is not running; start it and try again. If docker compose version says compose is not a command, install the Compose plugin from Docker's installation guide. On Windows, run every command in this course inside a WSL 2 terminal.

The first start downloads images: Grafana's is the largest, and together they take about 2.6 GB of disk once unpacked. On a slow connection, allow ten minutes or more for that one-time download.

A Short Docker Compose Primer

Docker Compose reads a file called compose.yaml that describes several containers and starts them together. You already know docker run; Compose writes the same choices down so you do not retype them. These are the ideas the stack uses:

  • A service is one kind of container, such as prometheus. Compose names the running container <project>-<service>-1, for example pmg-prometheus-1.
  • image: names the image to run. build: tells Compose to build an image from a folder containing a Dockerfile instead of downloading it.
  • ports: publishes ports, written host-address:host-port:container-port.
  • volumes: attaches storage: either a folder from your computer (a bind mount, written with a path such as ./prometheus) or a named volume.
  • environment: sets environment variables inside the container. A value written as ${NAME} is read from your shell or from a file called .env next to compose.yaml.
  • The project name prefixes everything Compose creates. Ours is set to pmg inside the file, so it does not depend on your folder's name.

The commands you will use, always run from the folder containing compose.yaml:

CommandEffect
docker compose up -dBuild or download what is missing, create and start every service in the background
docker compose psList this project's containers and their state
docker compose logs <service>Show a service's output
docker compose stopStop containers, keep them and all data
docker compose startStart stopped containers again
docker compose downRemove containers and the network, keep named volumes
docker compose down -vAlso delete this project's named volumes and their data

Create the Practice Folder

Create the folder and its subfolders, then move into it. Every command in the rest of this lesson runs from ~/pmg-practice.

mkdir -p ~/pmg-practice/prometheus ~/pmg-practice/shop ~/pmg-practice/tests
cd ~/pmg-practice

Now create each file below with your editor, copying the content exactly. Each is explained after it is shown.

The Compose file

Create compose.yaml with this content (complete file):

name: pmg

services:
  prometheus:
    image: prom/prometheus:v3.13.5
    command:
      - --config.file=/etc/prometheus/prometheus.yml
      - --web.enable-lifecycle
    ports:
      - "127.0.0.1:19090:9090"
    volumes:
      - ./prometheus:/etc/prometheus:ro
      - prometheus-data:/prometheus

  grafana:
    image: grafana/grafana:13.2.4
    environment:
      GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:?Set GRAFANA_ADMIN_PASSWORD in .env}
    ports:
      - "127.0.0.1:19300:3000"
    volumes:
      - grafana-data:/var/lib/grafana

  shop:
    build: ./shop
    image: pmg-shop:course
    ports:
      - "127.0.0.1:19200:8000"

  loadgen:
    image: pmg-shop:course
    pull_policy: never
    command: ["python", "-u", "loadgen.py"]
    depends_on:
      - shop

volumes:
  prometheus-data:
  grafana-data:

Reading it service by service:

  • prometheus runs the pinned image prom/prometheus:v3.13.5. The command list replaces the image's default arguments: --config.file says where to read the configuration, and --web.enable-lifecycle allows you to tell Prometheus to reload its configuration over HTTP, which a later lesson uses. Because command replaces all default arguments, the configuration path must be given here even though it matches the image's usual location. ./prometheus:/etc/prometheus:ro mounts your prometheus folder into the container read-only (:ro): you edit the configuration on your computer, and Prometheus can read but never change it. prometheus-data:/prometheus puts Prometheus's database in a named volume.
  • grafana runs grafana/grafana:13.2.4. Grafana reads settings from environment variables named GF_<section>_<key>, so GF_SECURITY_ADMIN_PASSWORD sets the password of the built-in admin user. Its value comes from your .env file. The :? form makes Compose refuse to start with the message after ? if the variable is missing, instead of silently starting Grafana with its well-known default password.
  • shop is built from the shop folder and tagged pmg-shop:course.
  • loadgen reuses that same image but runs a different program. pull_policy: never tells Compose not to look for pmg-shop:course on Docker Hub: the image only exists because the shop service builds it. Without this line, docker compose pull fails with "pull access denied for pmg-shop". depends_on starts the shop container before the load generator.

Every published port begins with 127.0.0.1:. Writing only "19090:9090" would publish on all of your computer's network addresses, and Prometheus has no sign-in: anyone on the same network could read all its data.

Prometheus's configuration

Create prometheus/prometheus.yml with this content (complete file):

global:
  scrape_interval: 15s
  evaluation_interval: 15s

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

  - job_name: shop
    static_configs:
      - targets: ["shop:8000"]

This tells Prometheus to collect metrics every 15 seconds from two places: itself (localhost:9090, inside its own container) and the shop (shop:8000, by service name). The next lesson explains what collecting, or scraping, means, and the Scraping and Discovery module explains every setting here. For now, notice that targets are written as host:port without http:// or a path.

The shop and the load generator

The shop is the service you will monitor for the whole course. Create shop/Dockerfile with this content (complete file):

FROM python:3.14.8-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY *.py ./
USER nobody
EXPOSE 8000
CMD ["python", "-u", "shop.py"]

It starts from a pinned Python image, installs the one dependency, copies the Python files and runs the shop as the unprivileged user nobody. The -u flag stops Python from buffering output, so docker compose logs shows messages immediately.

Create shop/requirements.txt with this content (complete file):

prometheus_client==0.26.0

prometheus_client is the official Python library for exposing metrics to Prometheus. Pinning the exact version means everyone builds the same image.

Create shop/shop.py with this content (complete file):

"""The course's practice shop: a small HTTP API to monitor.

Routes:
  GET /api/products, GET /api/orders       simulated work of 10 to 60 ms
  GET /healthz                             answers at once, no simulated work
  GET /admin/fault?latency=S&error_rate=R  sets injected faults (practice only)
  GET /metrics                             Prometheus exposition
"""
import json
import os
import random
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse

from prometheus_client import CONTENT_TYPE_LATEST, generate_latest

API_ROUTES = {"/api/orders", "/api/products"}
FAULT = {"latency": 0.0, "error_rate": 0.0}


class Handler(BaseHTTPRequestHandler):
    def log_message(self, *args):
        pass  # keep the container log for start-up messages and errors

    def send(self, code, body, content_type="application/json"):
        data = body if isinstance(body, bytes) else json.dumps(body).encode()
        self.send_response(code)
        self.send_header("Content-Type", content_type)
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def do_GET(self):
        url = urlparse(self.path)
        if url.path == "/metrics":
            self.send(200, generate_latest(), CONTENT_TYPE_LATEST)
        elif url.path == "/admin/fault":
            query = parse_qs(url.query)
            for key in FAULT:
                if key in query:
                    FAULT[key] = float(query[key][0])
            self.send(200, FAULT)
        elif url.path == "/healthz":
            self.send(200, {"status": "ok"})
        elif url.path in API_ROUTES:
            self.handle_api(url.path)
        else:
            self.send(404, {"error": "not found"})

    def handle_api(self, route):
        time.sleep(random.uniform(0.01, 0.06) + FAULT["latency"])
        if random.random() < FAULT["error_rate"]:
            self.send(500, {"route": route, "error": "injected fault"})
        else:
            self.send(200, {"route": route, "items": random.randint(1, 20)})


if __name__ == "__main__":
    port = int(os.environ.get("PORT", "8000"))
    print(f"shop listening on port {port}")
    ThreadingHTTPServer(("0.0.0.0", port), Handler).serve_forever()

You do not need to write Python in this lesson, but you will change this file in the next module, so it is worth reading its five parts:

  • The server (the block at the bottom) uses Python's built-in ThreadingHTTPServer, which handles each request in its own thread. It listens on 0.0.0.0, meaning every address inside the container; the 127.0.0.1 restriction is applied by the published port in compose.yaml, not here.
  • Routing (do_GET) looks at the request path and chooses what to do. /healthz answers immediately. The two API routes go to handle_api. Anything else gets a 404.
  • handle_api pretends to do work by sleeping 10 to 60 milliseconds, plus any injected latency, then fails with status 500 with probability error_rate. Both start at zero.
  • /admin/fault changes those two numbers. For example, /admin/fault?latency=0.4 adds 400 milliseconds to every API request until you set it back to 0. Changing state with a GET request is a shortcut for practice, not a design to copy into real services.
  • /metrics returns generate_latest(), the library's text rendering of every metric registered in the process. Right now the shop has defined no metrics of its own, so this page shows only the Python runtime metrics the library registers automatically. The next module adds request and latency metrics.

Create shop/loadgen.py with this content (complete file):

"""Practice load generator: a steady, bounded stream of requests to the shop."""
import os
import random
import time
import urllib.error
import urllib.request

TARGET = os.environ.get("TARGET", "http://shop:8000")
RATE = float(os.environ.get("RATE", "5"))  # requests per second, at most
PATHS = ["/api/products"] * 6 + ["/api/orders"] * 3 + ["/healthz", "/missing"]

print(f"sending about {RATE:g} requests per second to {TARGET}")
while True:
    try:
        urllib.request.urlopen(TARGET + random.choice(PATHS), timeout=5).read()
    except urllib.error.HTTPError:
        pass  # 404 and 500 answers are expected; the shop counts them
    except (urllib.error.URLError, OSError):
        time.sleep(2)  # the shop is not reachable yet, or was stopped
    time.sleep(1 / RATE)

It picks a path at random, weighted so that products are requested about twice as often as orders, with an occasional health check and a request for /missing that always returns 404. It pauses between requests, so it sends at most about five per second; because each request also takes time, the real rate is a little lower. If the shop is unreachable it waits two seconds and keeps trying, so stopping the shop never crashes the load generator.

The stack check and the ignore file

Create tests/check-stack.sh with this content (complete file):

#!/usr/bin/env bash
# Health check for the practice stack. Run it from your practice folder:
#   bash tests/check-stack.sh
# It only reads: it lists the Compose project's containers and sends GET
# requests to the stack's 127.0.0.1 ports. It changes nothing.
set -u
pass=0; fail=0
check() {
  if eval "$2" >/dev/null 2>&1; then echo "PASS  $1"; pass=$((pass + 1))
  else echo "FAIL  $1"; fail=$((fail + 1)); fi
}
query() { curl -s --get http://127.0.0.1:19090/api/v1/query --data-urlencode "query=$1"; }

check "at least 4 services of project pmg are running" \
  '[ "$(docker compose ps --status running --quiet | wc -l)" -ge 4 ]'
check "Prometheus is ready on 127.0.0.1:19090" 'curl -sf http://127.0.0.1:19090/-/ready'
check "Grafana answers /api/health on 127.0.0.1:19300" 'curl -sf http://127.0.0.1:19300/api/health'
check "shop answers /healthz on 127.0.0.1:19200" 'curl -sf http://127.0.0.1:19200/healthz'
check "shop /metrics returns Prometheus text" \
  'curl -sf http://127.0.0.1:19200/metrics | grep -q "^# TYPE "'
check "Prometheus scrapes the prometheus and shop jobs successfully" \
  'query "count(up{job=~\"prometheus|shop\"} == 1)" | grep -q "\"[2-9]\"\]"'
check "no target that Prometheus scrapes is down" \
  'query "up == 0" | grep -q "\"result\":\[\]"'

echo "$pass passed, $fail failed"
[ "$fail" -eq 0 ]

Each check line runs one test and prints PASS or FAIL. curl -sf fails when a page does not answer or answers with an error status. The last two checks ask Prometheus questions in its query language. The first is "how many targets of the prometheus and shop jobs were collected successfully?", and the answer must be at least 2 (one of each now; the shop job gains a second instance later in the course). The second is "is any target's last scrape a failure?", and the answer must be an empty list. You will learn to write such queries in the PromQL module; here it is enough to know what the checks mean. The same script works unchanged for the rest of the course.

Finally, create .gitignore with this content (complete file):

.env

This keeps your password file out of any Git repository you might make of the practice folder.

Set the Grafana Password

Grafana needs a password for its admin user. Generate a random local test password into .env and make the file readable only by you:

printf 'GRAFANA_ADMIN_PASSWORD=%s\n' "$(openssl rand -hex 12)" > .env
chmod 600 .env

openssl rand -hex 12 prints 24 random hexadecimal characters. This is a practice password for a service that only your computer can reach; do not reuse a real password here. To see it later, run cut -d= -f2 .env.

One behaviour to know now: Grafana applies this password only when its data volume is first created. After the first start, the password is stored inside pmg_grafana-data, and changing .env has no effect on it. The independent task at the end shows what that means in practice.

Start the Stack

From ~/pmg-practice:

docker compose up -d

Compose builds the shop image, downloads the Prometheus and Grafana images if you do not have them, creates the network and the two volumes, and starts the four containers. The end of its output looks like this (illustrative; build lines and timings vary):

 Image pmg-shop:course Built
 Network pmg_default Created
 Volume pmg_prometheus-data Created
 Volume pmg_grafana-data Created
 Container pmg-shop-1 Started
 Container pmg-prometheus-1 Started
 Container pmg-grafana-1 Started
 Container pmg-loadgen-1 Started

"Started" means the process inside each container was launched. It does not mean each program is ready to answer, which is the next thing to check.

Wait for Readiness

Prometheus usually answers within a few seconds. Grafana takes longer on its first start while it prepares its database; on the author's machine it took about 50 seconds. These commands wait for each, giving up after two and three minutes respectively:

for i in $(seq 1 60); do curl -sf http://127.0.0.1:19090/-/ready && break; sleep 2; done
for i in $(seq 1 90); do curl -sf http://127.0.0.1:19300/api/health && break; sleep 2; done

When ready, they print (illustrative; the commit value differs):

Prometheus Server is Ready.
{
  "database": "ok",
  "version": "13.2.4",
  "commit": "0e79aef9d91abf3bdadae9af15763029072fb45b"
}

/-/ready is Prometheus's readiness page: it answers only once Prometheus can serve queries. /api/health is Grafana's: "database": "ok" means its internal database is usable, and version confirms the pinned release. If a loop finishes without printing anything, the service did not become ready in time; see "When Something Differs" below.

Inspect What Is Running

List the containers:

docker compose ps

Illustrative output, with the columns that matter:

NAME               IMAGE                     SERVICE      STATUS         PORTS
pmg-grafana-1      grafana/grafana:13.2.4    grafana      Up 5 seconds   127.0.0.1:19300->3000/tcp
pmg-loadgen-1      pmg-shop:course           loadgen      Up 2 seconds   8000/tcp
pmg-prometheus-1   prom/prometheus:v3.13.5   prometheus   Up 5 seconds   127.0.0.1:19090->9090/tcp
pmg-shop-1         pmg-shop:course           shop         Up 5 seconds   127.0.0.1:19200->8000/tcp

Check three things: every service shows Up; IMAGE shows the pinned tags; PORTS shows 127.0.0.1: before every published port. The load generator lists 8000/tcp only because the image declares that port; it is not published, so there is no arrow to it from your computer.

Now ask the shop and its metrics page directly:

curl -s http://127.0.0.1:19200/healthz
curl -s http://127.0.0.1:19200/metrics | head -4

Illustrative output:

{"status": "ok"}
# HELP python_gc_objects_collected_total Objects collected during gc
# TYPE python_gc_objects_collected_total counter
python_gc_objects_collected_total{generation="0"} 316.0
python_gc_objects_collected_total{generation="1"} 0.0

The metrics page is plain text in Prometheus's exposition format: # HELP and # TYPE lines describe a metric, and each following line is one value. The numbers vary. A later lesson reads this format in detail.

Check the logs of the two services you built:

docker compose logs shop loadgen

You should see shop listening on port 8000 and sending about 5 requests per second to http://shop:8000. Nothing else is printed during normal operation.

Open http://127.0.0.1:19090 in your browser to see Prometheus's interface, and http://127.0.0.1:19300 for Grafana. Sign in to Grafana with the user name admin and the password from .env. If Grafana offers to change the password, you can skip that. Grafana is empty for now; it is connected to Prometheus in the Grafana module.

Finally, run the stack check:

bash tests/check-stack.sh

Success looks like this:

PASS  at least 4 services of project pmg are running
PASS  Prometheus is ready on 127.0.0.1:19090
PASS  Grafana answers /api/health on 127.0.0.1:19300
PASS  shop answers /healthz on 127.0.0.1:19200
PASS  shop /metrics returns Prometheus text
PASS  Prometheus scrapes the prometheus and shop jobs successfully
PASS  no target that Prometheus scrapes is down
7 passed, 0 failed

Seven passes means each container runs, each web page answers, and Prometheus has successfully collected metrics from both targets, with no target failing. The last two checks are the important ones: containers that run are not proof that monitoring works. If they fail right after starting, wait 15 seconds (one collection interval) and run the script again.

Stop, Resume and Reset

You will often pause the stack between lessons. The three ways to stop it differ in what they keep, and choosing the wrong one deletes work:

CommandContainersNamed volumes (stored samples, Grafana state)Use it when
docker compose stopStopped, keptKeptPausing between lessons
docker compose downRemovedKeptTidying up containers; history stays
docker compose down -vRemovedDeletedYou deliberately want a completely fresh start

The author checked this on the pinned stack. After stop and start, and after down and up -d, Prometheus still held every sample collected before. After down -v and up -d, it held only the samples collected since the new start, and Grafana was back to a first start with whatever password .env then contained.

Before any down -v, confirm you are in the right folder by running docker compose ps: it must list pmg- containers. The -v deletes only volumes that belong to this Compose project, never your other Docker data. Never use docker system prune or delete volumes by pattern to "clean up" for this course; those commands remove things that are not yours.

To resume after stop, run docker compose start. After down, run docker compose up -d. Either way, wait for readiness again before using the stack.

When Something Differs

Compose refuses to start with "required variable GRAFANA_ADMIN_PASSWORD is missing a value: Set GRAFANA_ADMIN_PASSWORD in .env". There is no .env next to compose.yaml, or it does not contain that variable. Create it as shown above, from ~/pmg-practice.

"no configuration file provided: not found". You ran a docker compose command outside ~/pmg-practice. Change into the folder and repeat.

"ports are not available: ... bind: address already in use". Something else on your computer already listens on that port. The author reproduced this by occupying 19090 before starting Prometheus. Find what uses the port (lsof -nP -iTCP:19090 -sTCP:LISTEN on macOS and Linux) and stop it, then run docker compose up -d again. Do not change the course ports unless you must; every lesson uses them.

Grafana's readiness loop finishes without output. Look at docker compose logs grafana for a line containing level=error. On first start, Grafana can simply be slow on a busy computer: run the loop again. A Grafana container that exits immediately shows Exited in docker compose ps; its log names the reason.

The image download stops making progress. Interrupt it with Ctrl+C and run docker compose up -d again; layers already downloaded are kept.

The last two checks of check-stack.sh fail but the others pass. Prometheus has not completed a collection yet (wait 15 seconds), or it cannot reach the shop. The next lesson shows where Prometheus reports exactly why a target cannot be collected.

Independent Task

Change the Grafana password and observe what happens:

  1. Generate a new password into .env with the same printf command as before.
  2. Recreate the Grafana container so it reads the new environment: docker compose up -d --force-recreate grafana, then wait for readiness.
  3. Try to sign in with the new password, then with the old one.

Before reading on, predict which password works, and decide how you would make Grafana use the new one.

Answer

The old password still works and the new one is rejected. The author confirmed this on the pinned version: after recreating the container with a changed .env, the original password returned success and the new one was refused with status 401. Grafana copied the password into its database in pmg_grafana-data on the first start and only reads the environment variable when that database is created.

To use the new password, reset Grafana's state only, leaving Prometheus's data alone:

docker compose rm -sf grafana
docker volume rm pmg_grafana-data
docker compose up -d grafana

rm -sf stops and removes only the Grafana container; docker volume rm deletes only Grafana's volume, which at this point in the course contains nothing you created. Wait for readiness and sign in with the new password. Later in the course, Grafana's dashboards and data source are kept as files precisely so that this kind of reset loses nothing.

A common mistake is to run docker compose down -v instead: that also deletes every sample Prometheus has collected.

Keep It Running

Leave the stack running for the next lesson, or pause it with docker compose stop and resume with docker compose start. Your folder now matches the course's starting point; this is also the state the Start Here checkpoint restores.

Check Your Understanding

  1. Why does compose.yaml publish 127.0.0.1:19090:9090 rather than 19090:9090?
  2. Containers are Up but the last two stack checks fail. Name one reason.
  3. You want to free memory overnight without losing any collected data. Which command do you use, and which must you avoid?

Answers

  1. 127.0.0.1 limits the port to your own computer. Without it, Docker publishes on every network address, and Prometheus, which has no sign-in, would be readable by anyone on your network.
  2. Prometheus has not completed its first collection yet, or it cannot reach the shop. A running container is not evidence that collection works.
  3. docker compose stop (or down, which also keeps volumes). Avoid docker compose down -v, which deletes the volumes holding Prometheus's samples and Grafana's state.

30 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy