Skip to content

Lesson 23 of 24Kubernetes

Project: A Containerised Link Shortener

Containerise a small link shortener on your own machine, stage by stage: a FastAPI app with tests, a multi-stage non-root image with a healthcheck, Compose with Postgres, a volume and a file secret, hardening and limits, then a CI pipeline that tests, scans and pushes a tagged image.

12 min read0/5 questions

You have learned each Docker idea on its own. This project puts them in the order you would use them on a real ticket. You will take a small link shortener from source code to a tested, scanned image in a registry, with a database next to it in Compose.

The app is deliberately small, so the containers get your attention. It has two services: a FastAPI API that turns long URLs into short codes and counts clicks, and Postgres that stores them. There is no frontend and no worker, on purpose.

This is a guided build. You type the files on your own machine and run the commands there. You need Docker Desktop or Docker Engine with the Compose plugin, uv, and a GitHub account for the last stage. One small checker in stage 4 runs right here in the page.

The plan: one image, two services, one pipeline

What you are building
You: curlYoucurlapi: UID 10001, read-onlyapiUID 10001, read-onlydb: postgres:17dbpostgres:17pgdata: named volumepgdatanamed volumedb_password: file secretdb_passwordfile secretGHCR: sha-tagged imageGHCRsha-tagged image:8000db:5432data/run/secrets/run/secretsimage

Only the API publishes a port. You reach it from the host at localhost:8000.

1/5

Stage 1: the app and its tests

Start with the code you are going to containerise, the same way Writing a Dockerfile began with its FastAPI project. Create the project with uv:

uv init --app shortlinkcd shortlinkuv add fastapi "uvicorn[standard]" "psycopg[binary]"uv add --dev pytest httpx2rm main.pymkdir app tests secrets

Each uv add updates pyproject.toml and writes uv.lock. The lock file matters later: the image installs exactly what it lists. httpx2 is the client behind FastAPI's TestClient; the Python Backend course explains why it replaced httpx. Add this at the end of pyproject.toml so pytest can import the app package:

pyproject.toml (add at the end)
[tool.pytest.ini_options]
pythonpath = ["."]

Create an empty app/__init__.py. The database code reads its password from a file whose path comes from DB_PASSWORD_FILE. That is the _FILE convention from Container Security in Depth, and it is why no password ever appears in docker inspect.

app/store.py
import os
from pathlib import Path
 
import psycopg
 
SCHEMA = """
CREATE TABLE IF NOT EXISTS links (
    code   text PRIMARY KEY,
    url    text NOT NULL,
    clicks integer NOT NULL DEFAULT 0
)
"""
 
 
def connect() -> psycopg.Connection:
    password = Path(os.environ["DB_PASSWORD_FILE"]).read_text().strip()
    return psycopg.connect(
        host=os.environ.get("DB_HOST", "db"),
        dbname=os.environ.get("DB_NAME", "links"),
        user=os.environ.get("DB_USER", "postgres"),
        password=password,
        connect_timeout=3,
    )
 
 
class PostgresStore:
    def init_schema(self) -> None:
        with connect() as conn:
            conn.execute(SCHEMA)
 
    def add(self, code: str, url: str) -> None:
        with connect() as conn:
            conn.execute("INSERT INTO links (code, url) VALUES (%s, %s)", (code, url))
 
    def resolve(self, code: str) -> str | None:
        with connect() as conn:
            row = conn.execute(
                "UPDATE links SET clicks = clicks + 1 WHERE code = %s RETURNING url",
                (code,),
            ).fetchone()
        return row[0] if row else None
 
    def stats(self, code: str) -> tuple[str, int] | None:
        with connect() as conn:
            row = conn.execute(
                "SELECT url, clicks FROM links WHERE code = %s", (code,)
            ).fetchone()
        return (row[0], row[1]) if row else None

The routes get the store through Depends, so tests can swap in a fake. /healthz checks only that the process answers. It does not touch the database, which keeps it a good liveness check later.

app/main.py
import secrets
import string
from contextlib import asynccontextmanager
 
from fastapi import Depends, FastAPI, HTTPException
from fastapi.responses import RedirectResponse
from pydantic import BaseModel, HttpUrl
 
from app.store import PostgresStore
 
ALPHABET = string.ascii_letters + string.digits
store = PostgresStore()
 
 
def get_store() -> PostgresStore:
    return store
 
 
@asynccontextmanager
async def lifespan(app: FastAPI):
    store.init_schema()
    yield
 
 
app = FastAPI(title="shortlink", lifespan=lifespan)
 
 
class NewLink(BaseModel):
    url: HttpUrl
 
 
@app.get("/healthz")
def healthz() -> dict[str, str]:
    return {"status": "ok"}
 
 
@app.post("/links", status_code=201)
def create_link(body: NewLink, db: PostgresStore = Depends(get_store)) -> dict[str, str]:
    code = "".join(secrets.choice(ALPHABET) for _ in range(7))
    db.add(code, str(body.url))
    return {"code": code, "url": str(body.url)}
 
 
@app.get("/links/{code}")
def link_stats(code: str, db: PostgresStore = Depends(get_store)) -> dict[str, str | int]:
    found = db.stats(code)
    if found is None:
        raise HTTPException(status_code=404, detail="no such link")
    url, clicks = found
    return {"code": code, "url": url, "clicks": clicks}
 
 
@app.get("/{code}")
def follow(code: str, db: PostgresStore = Depends(get_store)) -> RedirectResponse:
    url = db.resolve(code)
    if url is None:
        raise HTTPException(status_code=404, detail="no such link")
    return RedirectResponse(url, status_code=307)
tests/test_links.py
from fastapi.testclient import TestClient
 
from app.main import app, get_store
 
 
class FakeStore:
    def __init__(self) -> None:
        self.rows: dict[str, list] = {}
 
    def add(self, code: str, url: str) -> None:
        self.rows[code] = [url, 0]
 
    def resolve(self, code: str) -> str | None:
        if code not in self.rows:
            return None
        self.rows[code][1] += 1
        return self.rows[code][0]
 
    def stats(self, code: str) -> tuple[str, int] | None:
        row = self.rows.get(code)
        return (row[0], row[1]) if row else None
 
 
def make_client() -> TestClient:
    fake = FakeStore()
    app.dependency_overrides[get_store] = lambda: fake
    return TestClient(app)  # no "with": the lifespan, and Postgres, never start
 
 
def test_shorten_follow_and_count() -> None:
    client = make_client()
    created = client.post("/links", json={"url": "https://example.com/docs"})
    assert created.status_code == 201
    code = created.json()["code"]
 
    hop = client.get(f"/{code}", follow_redirects=False)
    assert hop.status_code == 307
    assert hop.headers["location"] == "https://example.com/docs"
    assert client.get(f"/links/{code}").json()["clicks"] == 1
 
 
def test_rejects_bad_urls_and_unknown_codes() -> None:
    client = make_client()
    assert client.post("/links", json={"url": "not a url"}).status_code == 422
    assert client.get("/nope123", follow_redirects=False).status_code == 404
uv run pytest -q

Check: the last line reads 2 passed. The tests never need a database, which means they can run inside a build stage in stage 2.

Stage 2: a multi-stage image that runs as non-root

Now the Dockerfile. It combines four lessons. Dockerizing a Full-Stack App gave you the uv build stage and the --target test stage. BuildKit, Cache Mounts and Advanced Multi-Stage Builds added the cache mount. Docker in Production gave you the healthcheck and the exec-form CMD. Container Security in Depth gave you a numeric UID and app code owned by root.

Dockerfile
# syntax=docker/dockerfile:1
FROM python:3.13-slim AS build
COPY --from=ghcr.io/astral-sh/uv:0.13.5 /uv /bin/uv
ENV UV_COMPILE_BYTECODE=1 UV_LINK_MODE=copy
WORKDIR /app
COPY pyproject.toml uv.lock ./
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --locked --no-dev --no-install-project
COPY app/ ./app/
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --locked --no-dev
 
FROM build AS test
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --locked
COPY tests/ ./tests/
RUN uv run pytest -q
 
FROM python:3.13-slim AS runtime
RUN useradd --uid 10001 --no-create-home --shell /usr/sbin/nologin app
WORKDIR /app
COPY --from=build /app/.venv /app/.venv
COPY --from=build /app/app ./app
ENV PATH="/app/.venv/bin:$PATH"
USER 10001:10001
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
  CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=2)"]
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

The order follows Image Layers and the Build Cache: the lock file and the dependency install come before the source, so an edit to app/main.py reuses the install layer. The runtime stage copies only the virtual environment and the code. uv and the tests stay behind. The image tag for uv changes often, so check the uv releases page for the current one.

Keep the build context small with a .dockerignore, as Writing a Dockerfile showed. The secrets/ line matters most: the password file must never reach the builder.

.dockerignore
.git
.venv
__pycache__
.pytest_cache
secrets/
.env
compose*.yaml

Build the test stage, then the runtime image:

docker build --target test .docker build --target runtime -t shortlink-api:dev .docker run --rm --entrypoint id shortlink-api:devdocker run --rm shortlink-api:dev

Check: the first build ends with pytest printing 2 passed. If a test fails, the build fails, which is the point. id prints uid=10001(app) gid=10001(app) groups=10001(app). The last command fails, and that is the right result. You see a KeyError for DB_PASSWORD_FILE, then ERROR: Application startup failed. Exiting. The image works; it just has no database yet. docker image ls shortlink-api should show a size in the low hundreds of MB. Most of that is the slim Python base.

Stage 3: Compose with Postgres, a volume and a secret

The app refuses to start without its database, so start order matters. Docker Compose showed you the fix: a healthcheck on Postgres and condition: service_healthy on the API. Volumes and Networking explains why the API uses db as the host name and why only the API publishes a port.

compose.yaml
name: shortlink
 
services:
  api:
    build:
      context: .
      target: runtime
    image: ${API_IMAGE:-shortlink-api:dev}
    ports:
      - "8000:8000"
    environment:
      DB_HOST: db
      DB_NAME: links
      DB_USER: postgres
      DB_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password
    depends_on:
      db:
        condition: service_healthy
        restart: true
    restart: unless-stopped
 
  db:
    image: postgres:17
    environment:
      POSTGRES_DB: links
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres -d links"]
      interval: 5s
      timeout: 3s
      retries: 10
 
volumes:
  pgdata:
 
secrets:
  db_password:
    file: ./secrets/db_password.txt

Three details are easy to miss. restart: true under depends_on restarts the API when Compose restarts or recreates db, so the API never keeps a dead connection. Postgres reads POSTGRES_PASSWORD_FILE only when it initialises an empty volume, and the API reads the same file on every connect, so the two always agree on a fresh start. And the database has no ports: entry. Nothing on your machine can reach it except through the API, which is the same rule Volumes and Networking drew between published and internal ports.

image: uses a default with ${API_IMAGE:-...}, the interpolation from Docker Compose. Locally it names the image you build. In CI you will point it at the image the pipeline built. Add secrets/ to .gitignore, then create the password and start the stack:

openssl rand -hex 16 > secrets/db_password.txtdocker compose up -d --build --waitdocker compose pscurl -s -X POST localhost:8000/links -H "content-type: application/json" -d '{"url": "https://example.com/docs"}'

--wait returns only when every service with a healthcheck is healthy. The POST returns your code, which is random:

{"code":"Mbs4oZl","url":"https://example.com/docs"}

Follow it and read the count, using your own code:

curl -s -o /dev/null -w "%{http_code} %{redirect_url}\n" localhost:8000/Mbs4oZlcurl -s localhost:8000/links/Mbs4oZl
307 https://example.com/docs
{"code":"Mbs4oZl","url":"https://example.com/docs","clicks":1}

Check: docker compose ps shows both services with (healthy) in the status column. Now prove the volume works: run docker compose down, then docker compose up -d --wait, and ask for the stats again. The link and its count are still there. docker compose down -v would delete the volume and the data with it.

Predict the outputShell

You followed the short link twice, so it shows 2 clicks. What does the last command print?

docker compose down
docker compose up -d --wait
curl -s localhost:8000/Mbs4oZl -o /dev/null
docker compose down -v
docker compose up -d --wait
curl -s localhost:8000/links/Mbs4oZl
Need a nudge? Hints walk you through it.

Stage 4: harden it and set limits

The stack works. Now take away everything the API does not need. Container Security in Depth gives the list, and Resource Limits, Restarts and Logging Drivers sets the limits. Add these keys to the api service:

compose.yaml (add under services.api)
    read_only: true
    tmpfs:
      - /tmp
    cap_drop: [ALL]
    security_opt:
      - no-new-privileges:true
    pids_limit: 100
    deploy:
      resources:
        limits:
          memory: 256M
          cpus: "0.5"

The API writes no files, so a read-only root costs nothing. The tmpfs gives libraries a writable /tmp in case they need one. Recreate it and test the hardening from inside:

docker compose up -d --waitdocker compose exec api iddocker compose exec api touch /app/notes.txtdocker stats --no-stream

Check: id still prints UID 10001, and touch fails with Read-only file system. docker stats shows the API's memory against a 256MiB limit. Take a reading after a few requests, because Resource Limits, Restarts and Logging Drivers warns that a limit set too low ends in exit 137.

Before you move on, run the same checks a reviewer would. This checker reads a copy of your Dockerfile and the api service. Change USER 10001:10001 to USER root, or delete read_only, and run it again to see it fail.

Pythonpreflight.py
DOCKERFILE = """FROM python:3.13-slim AS runtimeRUN useradd --uid 10001 --no-create-home --shell /usr/sbin/nologin appWORKDIR /appCOPY --from=build /app/.venv /app/.venvCOPY --from=build /app/app ./appENV PATH="/app/.venv/bin:$PATH"USER 10001:10001HEALTHCHECK CMD ["python", "-c", "..."]CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]""" API_SERVICE = { "read_only": True, "cap_drop": ["ALL"], "security_opt": ["no-new-privileges:true"], "environment": {"DB_HOST": "db", "DB_PASSWORD_FILE": "/run/secrets/db_password"}, "deploy": {"resources": {"limits": {"memory": "256M"}}},} lines = [l.strip() for l in DOCKERFILE.strip().splitlines()]users = [l.split()[1] for l in lines if l.startswith("USER ")]cmd = next((l for l in reversed(lines) if l.startswith("CMD ")), "")env = API_SERVICE.get("environment", {}) checks = [ ("final USER is a numeric non-root UID", bool(users) and users[-1].split(":")[0].isdigit() and users[-1].split(":")[0] != "0"), ("HEALTHCHECK is set", any(l.startswith("HEALTHCHECK ") for l in lines)), ("CMD uses exec form, so the app gets SIGTERM", cmd.startswith("CMD [")), ("no secret values in ENV", not any(l.startswith("ENV ") and ("PASSWORD=" in l or "TOKEN=" in l) for l in lines)), ("root filesystem is read-only", API_SERVICE.get("read_only") is True), ("all capabilities dropped", "ALL" in API_SERVICE.get("cap_drop", [])), ("passwords arrive as files", not any(k.endswith("PASSWORD") for k in env)), ("memory limit set", "memory" in API_SERVICE.get("deploy", {}).get("resources", {}).get("limits", {})),] for name, passed in checks: print("PASS" if passed else "FAIL", name)print(sum(p for _, p in checks), "of", len(checks), "checks pass")
Output
Press Run (⌘ Enter) to see what happens.

When it breaks

Something in stages 3 and 4 usually goes wrong the first time. Use the triage order from Debugging Containers: status and exit code first, then logs, then a look inside. These three failures cover most first runs.

The API restarts in a loop with password authentication failed. You changed secrets/db_password.txt after the first start. Postgres kept the password from the day it initialised the volume, and the API now sends the new one. On a dev machine the fix is docker compose down -v and a fresh start. On a real database you would change the password inside Postgres instead, because -v deletes the data.

The API exits with PermissionError on /run/secrets/db_password. This happens on Linux hosts. A Compose file secret is a bind mount, so it keeps the host file's owner and mode, and UID 10001 cannot read a file that only your user can read. Make the file readable with chmod 644 for local work. Production platforms mount secrets with the right owner for you.

docker compose ps shows the API as (unhealthy), yet curl works. The healthcheck runs inside the container, so it must call the port the app listens on inside the container, 8000, at 127.0.0.1. A healthcheck that uses the published host port, or a host name the container cannot resolve, fails while the app is fine. Run docker inspect --format "{{json .State.Health}}" shortlink-api-1 to read the last few check results and their output.

When a container exits instead, check the code before the logs. docker compose ps -a shows it. Exit 1 is the app failing, and the logs say why. Exit 137 means it was killed, usually by the memory limit, and Resource Limits, Restarts and Logging Drivers shows how to confirm that with docker inspect.

Quick check
You remove the depends_on block from api and run docker compose up -d on a fresh volume. What is the most likely result?
Need a nudge? A hint rules out a wrong answer.

Stage 5: CI that tests, scans and pushes a tagged image

The last stage is the pipeline from Docker in Production, with the scan from Scanning, SBOMs and Signed Images and the smoke test from the "Compose in CI" part of Docker Compose. It pushes to GitHub Container Registry with the job's own GITHUB_TOKEN, so there is no stored password, the habit Registries and Image Distribution asks for. Pull requests run every check but push nothing.

.github/workflows/image.yml
name: image
on:
  push:
    branches: [main]
    tags: ["v*"]
  pull_request:
 
permissions:
  contents: read
  packages: write
 
env:
  IMAGE: ghcr.io/${{ github.repository }}
  API_IMAGE: shortlink-api:ci
  COMPOSE_PROJECT_NAME: ci-${{ github.run_id }}
 
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: docker/setup-buildx-action@v4
 
      - name: Unit tests inside the image
        uses: docker/build-push-action@v7
        with:
          context: .
          target: test
          cache-from: type=gha
 
      - name: Build the runtime image
        uses: docker/build-push-action@v7
        with:
          context: .
          target: runtime
          load: true
          tags: shortlink-api:ci
          cache-from: type=gha
          cache-to: type=gha,mode=max
 
      - name: Smoke test the whole stack
        run: |
          mkdir -p secrets
          openssl rand -hex 16 > secrets/db_password.txt
          chmod 644 secrets/db_password.txt
          docker compose up -d --no-build --wait --wait-timeout 120
          curl -fsS -X POST localhost:8000/links \
            -H 'content-type: application/json' \
            -d '{"url": "https://example.com"}'
 
      - name: Logs on failure
        if: failure()
        run: docker compose logs --no-color --tail 200
 
      - name: Scan before pushing
        uses: aquasecurity/trivy-action@v0.36.0 # pin to the release's full commit SHA
        with:
          image-ref: shortlink-api:ci
          severity: CRITICAL
          ignore-unfixed: true
          exit-code: "1"
 
      - id: meta
        uses: docker/metadata-action@v6
        with:
          images: ${{ env.IMAGE }}
          tags: |
            type=sha
            type=semver,pattern={{version}}
            type=ref,event=branch
 
      - uses: docker/login-action@v4
        if: github.event_name != 'pull_request'
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
 
      - name: Push
        if: github.event_name != 'pull_request'
        uses: docker/build-push-action@v7
        with:
          context: .
          target: runtime
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha

A few lines need a reason. chmod 644 matters on Linux, where a Compose file secret is a bind mount. The API runs as UID 10001, so it needs read access to a file the runner created. --no-build makes Compose use the image CI just built, through API_IMAGE. The push step builds the runtime target again, but every layer comes from the builder's cache, so it pushes the same layers you tested and scanned. Scanning, SBOMs and Signed Images explains why the Trivy action should be pinned to a full commit SHA. Look the SHA up on the action's releases page.

Notice what the pipeline never does. It never stores a registry password, because GITHUB_TOKEN is issued for this one job and expires with it. It never pushes from a pull request, because code from a fork should not be able to write to your registry. And it never tags latest. A moving tag cannot tell you which code is running, while sha-1a2b3c4 points at exactly one commit. When you later deploy this image, deploy it by digest, as Registries and Image Distribution recommends.

Commit, push to a new GitHub repo, and watch the Actions tab.

Check: the run is green. On your repo page, under Packages, the image has two tags: sha- followed by seven characters of the commit, and main. A new GHCR package is private by default. Pull it by the SHA tag from the run, then check what was pushed:

docker pull ghcr.io/<you>/shortlink:sha-1a2b3c4docker buildx imagetools inspect ghcr.io/<you>/shortlink:sha-1a2b3c4

The inspect output shows the digest. That digest, not main, is what a deploy should point at. Push a tag like v1.0.0 and a third tag, 1.0.0, appears for the same digest.

Put it in order6 steps

Put the pipeline's steps in the order the workflow runs them, and the reason for that order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Match the pairs0/6 matched

Match each requirement to the line in this project that meets it.

Choose an item, then its match on the other side.
Quick check
A teammate suggests environment: DB_PASSWORD: ${DB_PASSWORD} instead of the file secret, because it is shorter. What is the strongest reason to keep the file?
Need a nudge? A hint rules out a wrong answer.

Make it yours

The project works. These make it something worth showing:

  • Add a worker. Move click counting to a second service that reads from a Redis queue, with its own healthcheck and memory limit. Then debug it when it exits, using the triage order from Debugging Containers.
  • Sign and attest. Add an SBOM, provenance and a keyless cosign sign on the pushed digest, as in Scanning, SBOMs and Signed Images, and show cosign verify in your README.
  • Build for both platforms. Push one tag for amd64 and arm64 with Multi-Architecture Images (amd64 and arm64), and check that psycopg[binary] has wheels for both.
  • A real dev loop. Add compose.override.yaml with watch mode and a dev target, following Compose for Local Development.
  • Run it on Kubernetes. Write a Deployment, a Service and a Secret for kind, with the probes from Config, Secrets, Probes and Autoscaling. /healthz is already a safe liveness check; add a readiness check that does touch the database.

When you write it up, the Interview Prep lesson Writing Project Case Studies shows how to turn a project like this into a short case study.

Key terms
multi-stage build
A Dockerfile with several FROM stages, where the final image copies only what it needs from earlier ones.
build target
The stage docker build --target stops at, used here to run tests in a stage that never ships.
healthcheck
A command the engine runs inside a container on a schedule to mark it healthy or unhealthy.
named volume
Storage managed by Docker that outlives containers, removed only by docker volume rm or down -v.
file secret
A secret mounted as a file under /run/secrets, read by the app instead of an environment variable.
smoke test
A quick end-to-end check that the real stack starts and answers one request, run before deeper checks or a release.
SHA tag
An image tag built from the git commit, so every image points back to the exact code it came from.

You now have one app through the whole path, from source to a scanned, tagged image. The wrap-up next walks a bigger app through every unit of the course, all the way to a cluster.