TExcelTAD
Home › Docker › Docker Mini Project

Docker Mini Project

In this project you containerise a small but realistic web application: a notes API written in Python, backed by PostgreSQL, and run together with Docker Compose. It uses most of the course: a multi-stage Dockerfile, a non-root user, a healthcheck, a .dockerignore, environment-based configuration, a named volume, two networks, depends_on with a health condition, restart policies, resource limits and a debug profile.

The finished project folder:

text
notes/
├── app.py              # WSGI entry point (gunicorn app:app)
├── notes.py            # the application: storage + HTTP handling
├── requirements.txt
├── Dockerfile
├── .dockerignore
├── compose.yaml
├── .env.example        # copy to .env and fill in
└── smoke_test.py

The real files are shown in normal code blocks: copy them to a folder and run them on a machine with Docker. The runnable playgrounds test the same application logic in the browser, using SQLite in place of PostgreSQL.

Step 1: The application

The app is plain WSGI (the standard Python web-server interface) so it needs no web framework. A NoteStore class wraps the database; it works with any DB-API connection, which lets us test it with SQLite here and run it on PostgreSQL in the container.

python · try it yourself
import io
import json
import sqlite3

DIALECTS = {
    "sqlite":   {"param": "?",  "id": "INTEGER PRIMARY KEY AUTOINCREMENT"},
    "postgres": {"param": "%s", "id": "INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY"},
}

class NoteStore:
    def __init__(self, conn, dialect):
        self.conn, self.d = conn, DIALECTS[dialect]

    def init(self):
        self.conn.execute(f"CREATE TABLE IF NOT EXISTS notes (id {self.d['id']}, text TEXT NOT NULL)")

    def add(self, text):
        row = self.conn.execute(f"INSERT INTO notes (text) VALUES ({self.d['param']}) RETURNING id", (text,)).fetchone()
        return {"id": row[0], "text": text}

    def all(self):
        return [{"id": i, "text": t} for i, t in self.conn.execute("SELECT id, text FROM notes ORDER BY id")]

def make_app(store):
    def app(environ, start_response):
        method, path = environ["REQUEST_METHOD"], environ["PATH_INFO"]
        if path == "/health":
            status, body = "200 OK", {"status": "ok"}
        elif path == "/notes" and method == "GET":
            status, body = "200 OK", store.all()
        elif path == "/notes" and method == "POST":
            size = int(environ.get("CONTENT_LENGTH") or 0)
            data = json.loads(environ["wsgi.input"].read(size) or b"{}")
            text = str(data.get("text", "")).strip()
            if text:
                status, body = "201 Created", store.add(text)
            else:
                status, body = "400 Bad Request", {"error": "text is required"}
        else:
            status, body = "404 Not Found", {"error": f"no route for {method} {path}"}
        payload = json.dumps(body).encode()
        start_response(status, [("Content-Type", "application/json"), ("Content-Length", str(len(payload)))])
        return [payload]
    return app

# --- a tiny test client: call the WSGI app directly, no server needed ---
def call(app, method, path, body=None):
    raw = json.dumps(body).encode() if body is not None else b""
    environ = {"REQUEST_METHOD": method, "PATH_INFO": path,
               "CONTENT_LENGTH": str(len(raw)), "wsgi.input": io.BytesIO(raw)}
    result = {}
    chunks = app(environ, lambda status, headers: result.update(status=status))
    print(f"{method:<6} {path:<8} -> {result['status']:<16} {b''.join(chunks).decode()}")

store = NoteStore(sqlite3.connect(":memory:"), "sqlite")
store.init()
app = make_app(store)
call(app, "GET", "/health")
call(app, "POST", "/notes", {"text": "Buy milk"})
call(app, "POST", "/notes", {"text": "Ship v1.0"})
call(app, "POST", "/notes", {"text": "   "})
call(app, "GET", "/notes")
call(app, "DELETE", "/notes")
GET    /health  -> 200 OK           {"status": "ok"}
POST   /notes   -> 201 Created      {"id": 1, "text": "Buy milk"}
POST   /notes   -> 201 Created      {"id": 2, "text": "Ship v1.0"}
POST   /notes   -> 400 Bad Request  {"error": "text is required"}
GET    /notes   -> 200 OK           [{"id": 1, "text": "Buy milk"}, {"id": 2, "text": "Ship v1.0"}]
DELETE /notes   -> 404 Not Found    {"error": "no route for DELETE /notes"}

In the project, everything above the test client goes into notes.py. The entry point app.py connects to PostgreSQL using the DATABASE_URL environment variable:

python
# app.py
import os
import psycopg
from notes import NoteStore, make_app

conn = psycopg.connect(os.environ["DATABASE_URL"], autocommit=True)
store = NoteStore(conn, "postgres")
store.init()
app = make_app(store)
text
# requirements.txt
gunicorn==23.0.0
psycopg[binary]==3.2.9

Step 2: Configuration from the environment

Before writing the Dockerfile, decide what is configurable. The container will receive DATABASE_URL (and optionally WORKERS); the app should fail fast with a readable message if it is wrong. This check could go at the top of app.py:

python · try it yourself
from urllib.parse import urlsplit

def check_database_url(url):
    if not url:
        return "error: DATABASE_URL is not set"
    parts = urlsplit(url)
    problems = []
    if parts.scheme not in ("postgres", "postgresql"):
        problems.append(f"scheme must be postgres://, got {parts.scheme or 'nothing'}://")
    if parts.hostname in ("localhost", "127.0.0.1"):
        problems.append("host is localhost: inside a container that is the container itself; use the service name (db)")
    if not parts.password:
        problems.append("no password given")
    if problems:
        return "error: " + "; ".join(problems)
    return f"ok: user={parts.username} host={parts.hostname} port={parts.port or 5432} db={parts.path.lstrip('/')}"

for url in ["postgres://notes:s3cret@db:5432/notes",
            "postgres://notes:s3cret@localhost:5432/notes",
            "mysql://notes@db/notes",
            None]:
    print(check_database_url(url))
ok: user=notes host=db port=5432 db=notes
error: host is localhost: inside a container that is the container itself; use the service name (db)
error: scheme must be postgres://, got mysql://; no password given
error: DATABASE_URL is not set

The second case is the most common mistake when moving an app into containers; catching it at start-up saves a lot of head-scratching.

Step 3: The Dockerfile and .dockerignore

A two-stage build: the first stage downloads and builds wheels for the dependencies, the second installs them into a clean slim image through a temporary bind mount (so the wheel files never become a layer), adds a non-root user and a healthcheck.

dockerfile
# syntax=docker/dockerfile:1
FROM python:3.12-slim AS build
WORKDIR /src
COPY requirements.txt .
RUN pip wheel --no-cache-dir --wheel-dir /wheels -r requirements.txt

FROM python:3.12-slim
ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1
RUN useradd --system --uid 10001 --no-create-home app
WORKDIR /app
RUN --mount=type=bind,from=build,source=/wheels,target=/wheels \
    pip install --no-cache-dir /wheels/*
COPY --chown=app:app notes.py app.py ./
USER 10001
EXPOSE 8000
HEALTHCHECK --interval=10s --timeout=3s --start-period=10s --retries=3 \
  CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health', timeout=2)" || exit 1
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "2", "--access-logfile", "-", "app:app"]
text
# .dockerignore
.git
.env
**/__pycache__
*.pyc
.venv
compose*.yaml
smoke_test.py

Let's check the Dockerfile against the rules from the course with a quick script, the kind of check you could run in CI:

python · try it yourself
DOCKERFILE = """\
FROM python:3.12-slim AS build
WORKDIR /src
COPY requirements.txt .
RUN pip wheel --no-cache-dir --wheel-dir /wheels -r requirements.txt
FROM python:3.12-slim
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1
RUN useradd --system --uid 10001 --no-create-home app
WORKDIR /app
RUN --mount=type=bind,from=build,source=/wheels,target=/wheels pip install --no-cache-dir /wheels/*
COPY --chown=app:app notes.py app.py ./
USER 10001
EXPOSE 8000
HEALTHCHECK --interval=10s CMD python -c "..." || exit 1
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "app:app"]
"""

lines = DOCKERFILE.splitlines()
words = [l.split()[0] for l in lines]
final_stage = lines[max(i for i, w in enumerate(words) if w == "FROM"):]
final_words = [l.split()[0] for l in final_stage]

checks = {
    "base images are pinned (no :latest)": all(":" in l.split()[1] and not l.split()[1].endswith(":latest")
                                               for l in lines if l.startswith("FROM")),
    "multi-stage build": words.count("FROM") >= 2,
    "dependencies installed before source is copied": final_words.index("RUN") < final_words.index("COPY"),
    "pip cache disabled": all("--no-cache-dir" in l for l in lines if "pip " in l),
    "runs as non-root numeric user": any(l.startswith("USER ") and l.split()[1].isdigit() and l.split()[1] != "0"
                                         for l in final_stage),
    "healthcheck present": "HEALTHCHECK" in final_words,
    "CMD uses exec form": final_stage[-1].startswith('CMD ["'),
    "server binds 0.0.0.0": "0.0.0.0" in final_stage[-1],
}
for label, ok in checks.items():
    print(f"[{'ok' if ok else '!!'}] {label}")
print(f"{sum(checks.values())}/{len(checks)} checks passed")
[ok] base images are pinned (no :latest)
[ok] multi-stage build
[ok] dependencies installed before source is copied
[ok] pip cache disabled
[ok] runs as non-root numeric user
[ok] healthcheck present
[ok] CMD uses exec form
[ok] server binds 0.0.0.0
8/8 checks passed

Build and try the image on its own (it will fail its healthcheck without a database, which is expected):

bash
docker build -t notes-api:1.0 .
docker image ls notes-api

Sample output:

text
REPOSITORY   TAG   IMAGE ID       CREATED          SIZE
notes-api    1.0   4e7a1c9b2d30   12 seconds ago   171MB

Step 4: compose.yaml

yaml
name: notes

services:
  api:
    build: .
    image: notes-api:1.0
    ports:
      - "127.0.0.1:8000:8000"
    environment:
      DATABASE_URL: postgres://notes:${DB_PASSWORD:?set DB_PASSWORD in .env}@db:5432/notes
    depends_on:
      db:
        condition: service_healthy
    networks: [frontend, backend]
    restart: unless-stopped
    mem_limit: 256m

  db:
    image: postgres:17
    environment:
      POSTGRES_USER: notes
      POSTGRES_DB: notes
      POSTGRES_PASSWORD: ${DB_PASSWORD:?set DB_PASSWORD in .env}
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U notes -d notes"]
      interval: 5s
      timeout: 3s
      retries: 10
    networks: [backend]
    restart: unless-stopped
    mem_limit: 512m

  adminer:
    image: adminer:5
    ports:
      - "127.0.0.1:8081:8080"
    networks: [frontend, backend]
    profiles: [debug]

networks:
  frontend: {}
  backend:
    internal: true

volumes:
  pgdata: {}
text
# .env.example  (copy to .env, which is in .gitignore)
DB_PASSWORD=change-me

The database publishes no port and sits on an internal network: only the API (and the optional Adminer UI) can reach it. The API's port is bound to 127.0.0.1. Before running it, let a script review the file the way you would in a code review:

python · try it yourself
import yaml

COMPOSE = """
name: notes
services:
  api:
    build: .
    ports: ["127.0.0.1:8000:8000"]
    environment: {DATABASE_URL: "postgres://notes:${DB_PASSWORD:?}@db:5432/notes"}
    depends_on: {db: {condition: service_healthy}}
    networks: [frontend, backend]
    restart: unless-stopped
    mem_limit: 256m
  db:
    image: postgres:17
    volumes: ["pgdata:/var/lib/postgresql/data"]
    healthcheck: {test: ["CMD-SHELL", "pg_isready -U notes -d notes"]}
    networks: [backend]
    restart: unless-stopped
    mem_limit: 512m
  adminer:
    image: adminer:5
    ports: ["127.0.0.1:8081:8080"]
    networks: [frontend, backend]
    profiles: [debug]
networks:
  frontend: {}
  backend: {internal: true}
volumes:
  pgdata: {}
"""

spec = yaml.safe_load(COMPOSE)
services = spec["services"]
issues = []

for name, s in services.items():
    for dep, cond in (s.get("depends_on") or {}).items():
        if dep not in services:
            issues.append(f"{name}: depends on unknown service {dep}")
        elif cond.get("condition") == "service_healthy" and "healthcheck" not in services[dep]:
            issues.append(f"{name}: waits for {dep} to be healthy, but {dep} has no healthcheck")
    for port in s.get("ports", []):
        if not port.startswith("127.0.0.1:"):
            issues.append(f"{name}: port {port} is published on all interfaces")
    for vol in s.get("volumes", []):
        source = vol.split(":")[0]
        if not source.startswith((".", "/")) and source not in spec.get("volumes", {}):
            issues.append(f"{name}: volume {source} is not declared")
    if "profiles" not in s and "restart" not in s:
        issues.append(f"{name}: long-running service without a restart policy")

default = [n for n, s in services.items() if "profiles" not in s]
print("starts by default:", default)
print("with --profile debug:", list(services))
for name in services:
    peers = [o for o in services if o != name and set(services[name]["networks"]) & set(services[o]["networks"])]
    print(f"{name:<8} can reach {peers}")
print("issues:", issues or "none")
starts by default: ['api', 'db']
with --profile debug: ['api', 'db', 'adminer']
api      can reach ['db', 'adminer']
db       can reach ['api', 'adminer']
adminer  can reach ['api', 'db']
issues: none

Step 5: Run it

bash
cp .env.example .env            # then edit DB_PASSWORD
docker compose up -d --build
docker compose ps
python smoke_test.py
docker compose logs api --tail 5

Sample output:

text
[+] Running 5/5
 ✔ Network notes_frontend   Created
 ✔ Network notes_backend    Created
 ✔ Volume "notes_pgdata"    Created
 ✔ Container notes-db-1     Healthy
 ✔ Container notes-api-1    Started

NAME          IMAGE           SERVICE   STATUS                    PORTS
notes-api-1   notes-api:1.0   api       Up 15 seconds (healthy)   127.0.0.1:8000->8000/tcp
notes-db-1    postgres:17     db        Up 21 seconds (healthy)   5432/tcp

The smoke test is a small script using only the standard library:

python
# smoke_test.py
import json
import urllib.request

BASE = "http://localhost:8000"

def request(method, path, body=None):
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(BASE + path, data=data, method=method,
                                 headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=5) as resp:
        return resp.status, json.loads(resp.read())

print(request("GET", "/health"))
print(request("POST", "/notes", {"text": "Hello from the host"}))
print(request("GET", "/notes"))

Step 6: Data survives the container

The notes live in PostgreSQL, whose files live in the pgdata volume. Recreating the API container (a new image version, a crash, docker compose up -d --force-recreate) loses nothing, but anything kept only in the API process's memory is gone. The model shows the difference: the database connection plays the role of the volume, and each make_app call is a fresh container.

python · try it yourself
import sqlite3

volume = sqlite3.connect(":memory:")           # survives: it stands for the pgdata volume
volume.execute("CREATE TABLE notes (id INTEGER PRIMARY KEY AUTOINCREMENT, text TEXT)")

def start_container(version):
    memory_cache = []                         # lives only as long as this container
    def handle(text):
        volume.execute("INSERT INTO notes (text) VALUES (?)", (text,))
        memory_cache.append(text)
        stored = volume.execute("SELECT COUNT(*) FROM notes").fetchone()[0]
        return f"[{version}] saved {text!r}: {stored} in db, {len(memory_cache)} in memory"
    return handle

api = start_container("api:1.0")
print(api("Buy milk"))
print(api("Ship v1.0"))
api = start_container("api:1.1")             # docker compose up -d with a new image
print(api("Write release notes"))
print("notes in db:", [t for (t,) in volume.execute("SELECT text FROM notes ORDER BY id")])
[api:1.0] saved 'Buy milk': 1 in db, 1 in memory
[api:1.0] saved 'Ship v1.0': 2 in db, 2 in memory
[api:1.1] saved 'Write release notes': 3 in db, 1 in memory
notes in db: ['Buy milk', 'Ship v1.0', 'Write release notes']

Try it for real:

bash
docker compose up -d --force-recreate api
curl -s localhost:8000/notes          # the notes are still there
docker compose down                   # containers + networks removed, volume kept
docker compose up -d && curl -s localhost:8000/notes   # still there
docker compose down -v                # this one deletes the data

Make it your own

  • Secrets instead of environment: switch POSTGRES_PASSWORD to POSTGRES_PASSWORD_FILE with a Compose secrets: entry, and teach app.py to read the password from /run/secrets/db_password.
  • Debug tools: docker compose --profile debug up -d and open Adminer at http://localhost:8081 (server db, user notes).
  • A dev override: add a compose.override.yaml that bind-mounts the source and runs gunicorn --reload.
  • CI: build the image in GitHub Actions, run smoke_test.py against docker compose up, then push notes-api:sha-<commit> to a registry.
  • Backups: a backup service with profiles: [ops] that runs pg_dump into a bind-mounted ./backups folder.

Test yourself

Why does the API use db (not localhost) as the host in DATABASE_URL?

  1. localhost is blocked by Docker
  2. Inside the API container, localhost is the API container itself; db is the database service's DNS name on the shared network
  3. PostgreSQL only accepts the name db
  4. It makes the connection encrypted

The db service publishes no port and is on an internal network. Who can connect to PostgreSQL?

  1. Anyone on the internet
  2. Only containers that share the backend network (api and adminer)
  3. Only the host
  4. Nobody

Why does the Dockerfile install wheels with RUN --mount=type=bind,from=build,... instead of COPY --from=build /wheels /wheels?

  1. COPY --from doesn't work with wheels
  2. The bind mount is only present during that RUN, so the wheel files never become a layer of the final image
  3. It is faster to type
  4. pip requires it