DEV Community

Visual Studio Learn
Visual Studio Learn

Posted on Originally published at visualstudiolearn.blogspot.com

Dockerize a FastAPI App: Dockerfile to Running Container

"It works on my machine." Every developer has said it — usually right before the same app breaks on a server, because something there is different: another Python version, a library missing, a file that never got copied.

Docker ends that argument. You pack the app together with everything it needs into one box — an image — and the box runs the same everywhere. In this post we dockerize a FastAPI app — from a plain Dockerfile to a running container — then pack it properly: the careless first try weighs 1.65 GB; the proper pack weighs 198 MB. Same app. Smaller box.

Get the code: all files from this post are free in the companion repo —
https://github.com/sajjad037/visual-studio-learn-code/tree/main/topic-14-docker-fastapi

The map

Four stops, and everything below is one of them:

  1. The recipe — a Dockerfile: a short text file that describes the box.
  2. The packed box — Docker reads the recipe and builds an image: your app, frozen together with Python and every library it needs.
  3. The running box — start the image and it becomes a container: your app, running, sealed off from the machine.
  4. The proof — we ask the app a question over the network, and it answers.

Step 1 — The app: a tiny notes API

Our app is deliberately small — one file, main.py, with three endpoints (an endpoint is one address the app answers on):

  • GET /health — answers "I am alive". Remember this one; Docker itself will use it later.
  • GET /notes — lists the notes.
  • POST /notes — adds a note.

The whole app — main.py with its three endpoints

Here is the whole file, to copy:

"""Tiny notes API — the demo app we dockerize in Topic #14.

Three endpoints are enough to prove a container works:
  GET  /health  -> {"status": "ok"}        (used by the Docker HEALTHCHECK)
  GET  /notes   -> list of notes
  POST /notes   -> add a note  {"text": "..."}
"""
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI(title="Notes API")

notes: list[dict] = [{"id": 1, "text": "Ship it in a container"}]


class NoteIn(BaseModel):
    text: str


@app.get("/health")
def health():
    return {"status": "ok"}


@app.get("/notes")
def list_notes():
    return notes


@app.post("/notes", status_code=201)
def add_note(note: NoteIn):
    new = {"id": len(notes) + 1, "text": note.text}
    notes.append(new)
    return new
Enter fullscreen mode Exit fullscreen mode

And requirements.txt — the three libraries, pinned:

fastapi==0.115.6
uvicorn==0.34.0
pydantic==2.10.4
Enter fullscreen mode Exit fullscreen mode

Step 2 — The first recipe: the naive Dockerfile

"Naive" just means the obvious first try — five working lines:

# NAIVE FIRST DRAFT — it works, but wait for the size.
FROM python:3.12
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Enter fullscreen mode Exit fullscreen mode

Line by line:

  • FROM python:3.12 — start from a ready-made box that already has Python inside.
  • WORKDIR /app — the folder the app lives in, inside the box.
  • COPY . . — copy everything from the project folder into the box.
  • RUN pip install — install the libraries listed in requirements.txt.
  • CMD — the command that starts the app when the box runs.

The naive Dockerfile — five lines

Step 3 — Build it and run it

One command builds the image, following the recipe line by line (the first build also downloads that Python box, so it takes a while):

docker build -f Dockerfile.naive -t notes-api:naive .
Enter fullscreen mode Exit fullscreen mode

The naive build finishing

Now start it. docker run takes the packed box and starts it as a running container. A port is a numbered door into the app — -p 8000:8000 connects door 8000 on the outside to door 8000 inside:

docker run -d --name notes -p 8000:8000 notes-api:naive
Enter fullscreen mode Exit fullscreen mode

And now the proof — we ask the app, over the network:

curl http://localhost:8000/health
# {"status":"ok"}

curl http://localhost:8000/notes
# [{"id":1,"text":"Ship it in a container"}]

curl -X POST http://localhost:8000/notes -H "Content-Type: application/json" -d '{"text":"Docker works"}'
# {"id":2,"text":"Docker works"}
Enter fullscreen mode Exit fullscreen mode

The proof — the health endpoint answers from inside the container

It works — exactly as it did on my machine. But look at the price tag:

docker images
Enter fullscreen mode Exit fullscreen mode

docker images — the naive pack weighs 1.65 GB

1.65 GB — for a notes app of about forty lines. The full Python box carries an entire operating system, compilers, and tools we never asked for — and all of it travels to every server, every deploy.

Step 4 — Pack properly: slim base, two stages

The new recipe fixes the weight in four moves:

# ---- Stage 1: install dependencies into a clean prefix ----
FROM python:3.12-slim AS builder
WORKDIR /build
COPY requirements.txt .
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt

# ---- Stage 2: the small runtime image that actually ships ----
FROM python:3.12-slim
RUN useradd --create-home appuser
WORKDIR /app
COPY --from=builder /install /usr/local
COPY --chown=appuser:appuser main.py .
USER appuser
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s \
  CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Enter fullscreen mode Exit fullscreen mode

The slim two-stage Dockerfile

  • Slim base. python:3.12-slim is the same Python on a diet: 179 MB instead of 1.62 GB.
  • Two stages — the big move. Stage 1 (builder) installs the libraries into one clean folder (/install). Stage 2 starts again from the fresh slim box and copies in only that finished folder — the builder's tools and mess never enter the box we ship.
  • .dockerignore guards the copy. It lists what stays out of the build context: caches (__pycache__/, *.pyc), git history (.git/), virtualenvs (.venv/), and the recipes themselves. The whole file:
__pycache__/
*.pyc
.git/
.venv/
Dockerfile*
docker-compose.yml
README.md
Enter fullscreen mode Exit fullscreen mode
  • Non-root user. The naive box ran everything as root, the all-powerful account. This box runs as an ordinary user (USER appuser) — if someone breaks the app, they land in a much smaller room. One catch, learned while making the video: copied files must belong to that user — that is why the COPY for main.py names its owner with --chown.
  • Health check. HEALTHCHECK makes Docker ask the health endpoint every thirty seconds — still alive? — and report the answer beside the container's name.

First, stop the naive container — docker rm -f notes — so its name and port 8000 are free again. Then rebuild and line the two boxes up side by side:

docker build -t notes-api:slim .
docker images
Enter fullscreen mode Exit fullscreen mode

Side by side — naive 1.65 GB, slim 198 MB

Naive: 1.65 GB. Slim: 198 MB — more than eight times smaller. Same app, same answers: we ran the same three questions against the slim container — health ok, notes listed, note added — and Docker's own status now adds one word: healthy.

Step 5 — The everyday workflow: docker compose

Day to day, you will not type the long commands. This compose file — six lines — describes the service once: build it here, call the image this, connect port 8000:

services:
  notes:
    build: .
    image: notes-api:slim
    ports:
      - "8000:8000"
Enter fullscreen mode Exit fullscreen mode

Then one command builds and starts everything, and one command brings it all down:

docker compose up -d
docker compose ps
curl http://localhost:8000/health
docker compose down
Enter fullscreen mode Exit fullscreen mode

docker compose ps — the container is up and healthy

Step 6 — Scan the box before you ship it

One last check before we call this box production-shaped: is anything inside it known to be dangerous? Trivy is a free scanner — it compares every package in the image against the public lists of known holes:

trivy image --severity HIGH,CRITICAL notes-api:slim
trivy image --severity HIGH,CRITICAL notes-api:naive
Enter fullscreen mode Exit fullscreen mode

Trivy report summary for the slim image

The honest result, measured on the recording machine:

  • Slim image: 51 serious findings (high or critical) — 48 in operating-system packages, 3 in a Python library.
  • Naive image: 505 — 502 in operating-system packages, and the same 3 in the Python library.

Two caveats, in plain words. A scan only finds holes that are already known and listed. And shrinking the box does not fix your own libraries: both images carry the same three findings in one Python library (Starlette — the scanner names the fixed version). Those you fix by updating the library. Smaller box, shorter list, less to patch — that is the real win.

Save this — the small-box checklist

  • Slim base — 179 MB, not 1.62 GB.
  • Two stages — build in one stage, ship only the result.
  • .dockerignore — keep the junk out.
  • Non-root user — a smaller room if something breaks in.
  • Health check — Docker keeps asking "still alive?"

Same app. Smaller box.

Your turn: your image is over a gigabyte — which two changes shrink it the most, and why? Tell me in the comments; I read every one.

Everything in this post was run for real on Docker 29.1.3 (Ubuntu 24.04) on 2026-11-18; image sizes and scan counts are the measured results of that run. Your numbers will be close, not identical — base images and vulnerability lists change over time.

Top comments (0)