Skip to content

Lesson 3 of 24Containers

Writing a Dockerfile

Write a clean Dockerfile for a FastAPI app, order it for fast cached builds, and keep the build context small.

16 min read0/6 questions

A Dockerfile is the recipe for your image, and small choices in it decide whether a rebuild takes 2 seconds or 2 minutes, and whether your image is 150 MB or 1.2 GB. You will write one for almost every service you ship, and "how do you make Docker builds fast?" is a common interview question.

The project we will containerise

A small FastAPI app. The layout matters, because Docker can only copy files that are inside the build context: the folder you hand to docker build.

fastapi-app
  • fastapi-app/
  • app/
  • __init__.py
  • main.pyFastAPI() lives here
  • tests/
  • test_main.py
  • .venv/local virtualenv, must NOT go in the image
  • .git/history, must NOT go in the image
  • .envsecrets, must NOT go in the image
  • .dockerignoretells Docker what to leave out
  • Dockerfilethe recipe
  • requirements.txtfastapi[standard], sqlalchemy, ...
app/main.py
from fastapi import FastAPI
 
app = FastAPI()
 
@app.get("/health")
def health() -> dict[str, str]:
    return {"status": "ok"}

Building it up, one instruction at a time

Every Dockerfile starts with FROM, the base image you build on. Pick an official image with a specific version, so builds are repeatable.

Dockerfile
FROM python:3.13-slim
 
WORKDIR /app

WORKDIR sets the current directory for every later instruction (and for the running container), creating it if needed. Never cd in a RUN line; it only lasts for that line.

Next, install dependencies. COPY <src> <dest> copies files from the build context into the image. RUN executes a shell command at build time and saves the result as a new layer.

Dockerfile
FROM python:3.13-slim
 
WORKDIR /app
 
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

--no-cache-dir stops pip from keeping its download cache inside the image, which would be dead weight. Now copy the code and say how to start the app.

Dockerfile
ARG PYTHON_VERSION=3.13
FROM python:${PYTHON_VERSION}-slim
 
ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1
 
WORKDIR /app
 
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
 
COPY app/ ./app/
 
RUN useradd --create-home appuser
USER appuser
 
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

The highlighted lines are new:

  • ARG is a build-time variable. You can override it with docker build --build-arg PYTHON_VERSION=3.14 .. It does not exist when the container runs.
  • ENV sets an environment variable that is baked into the image and present at runtime. PYTHONUNBUFFERED=1 makes print and logs appear immediately in docker logs.
  • USER appuser makes every later instruction and the running app use an unprivileged user instead of root. If someone breaks into your app, they are not root inside the container.
  • EXPOSE 8000 is documentation: it records which port the app listens on. It does not publish the port to your machine. You do that with -p at run time (next lesson).
  • CMD is the default command the container runs. Note --host 0.0.0.0: inside a container, 127.0.0.1 means "only this container", so uvicorn must listen on all interfaces or nothing outside can reach it.

Build and run it:

docker build -t myapi:1.0 .docker run --rm -p 8000:8000 myapi:1.0curl localhost:8000/health   # {"status":"ok"}
Match the pairs0/6 matched

Match each instruction to what it does.

Choose an item, then its match on the other side.

Layer caching: order is everything

Each instruction produces a layer, and Docker caches layers. On a rebuild, Docker walks the Dockerfile top to bottom. An instruction is a cache hit if the instruction text is unchanged, its parent layer is unchanged, and (for COPY) the copied files have the same contents. The first miss invalidates every layer after it, because each layer is built on top of the previous one.

Here is what happens when you change one line of app/main.py in our Dockerfile. Highlighted layers rebuild.

Good order: dependencies before source
  1. CMD uvicorn ...
  2. COPY app/ ./app/your code
  3. RUN pip install -r requirements.txtslow: about 40 s
  4. COPY requirements.txt .
  5. WORKDIR /app
  6. FROM python:3.13-slim

First build: everything runs. The pip install layer takes most of the time.

1/3
Bad order: source copied first
  1. CMD uvicorn ...
  2. RUN pip install -r requirements.txtslow: about 40 s
  3. COPY . .code AND requirements
  4. WORKDIR /app
  5. FROM python:3.13-slim

First build: same as before.

1/2

The rule: copy the files that change least first. Dependency manifests (requirements.txt, pyproject.toml and uv.lock, package.json and package-lock.json) go in, then the install step, then the source code.

Run this model of the cache. The cache key for each layer is a hash of the parent layer, the instruction, and the contents of any copied files. That chaining is exactly why one miss invalidates everything after it.

Pythonlayer_cache.py
import hashlib def build(dockerfile: list[str], files: dict[str, str], cache: set[str]) -> None: parent = "" for line in dockerfile: parts = [parent, line] if line.startswith("COPY"): src = line.split()[1] parts += [p + files[p] for p in sorted(files) if src == "." or p == src] key = hashlib.sha256("|".join(parts).encode()).hexdigest()[:8] print("CACHED" if key in cache else "BUILD ", line) cache.add(key) parent = key print() dockerfile = [ "FROM python:3.13-slim", "COPY requirements.txt .", "RUN pip install -r requirements.txt", "COPY . .",]files = {"requirements.txt": "fastapi", "main.py": "v1"}cache: set[str] = set() build(dockerfile, files, cache) # first buildfiles["main.py"] = "v2"build(dockerfile, files, cache) # code change
Output
Press Run (⌘ Enter) to see what happens.
Quick check
Using the good-order Dockerfile above, you change one line in app/main.py and rebuild. Which instructions actually run?
Need a nudge? A hint rules out a wrong answer.
Quick check
Your Dockerfile has RUN apt-get update on one line and, below it, RUN apt-get install -y curl. Months later you add git to the install line. What can go wrong?
Need a nudge? A hint rules out a wrong answer.

CMD, ENTRYPOINT, and the two forms

Both CMD and ENTRYPOINT define what runs when the container starts, and each comes in two forms.

Exec form (use this)Shell form
SyntaxCMD ["uvicorn", "app.main:app"]CMD uvicorn app.main:app
What runsuvicorn directly, as PID 1/bin/sh -c "uvicorn ...", sh is PID 1
Gets SIGTERM on docker stop?YesNo, sh does not forward it
Variable expansion like $PORTNoYes

The shell form looks friendlier, but your app never hears the shutdown signal, so docker stop waits 10 seconds and then kills it hard. Use the exec form (a JSON array with double quotes).

The difference between the two instructions:

  • ENTRYPOINT is the fixed program. Arguments after the image name in docker run are appended to it.
  • CMD is the default arguments (or the default command if there is no ENTRYPOINT). Arguments after the image name replace it.
Predict the outputShell

Given this Dockerfile, what does the last command print?

# Dockerfile
FROM alpine:3.20
ENTRYPOINT ["echo", "hello"]
CMD ["world"]

$ docker build -t greet .
$ docker run greet Ada
Need a nudge? Hints walk you through it.

The build context and .dockerignore

In docker build -t myapi:1.0 ., that final . is the build context. Docker sends the whole folder to the builder before it starts. Without a filter it would send your .git history, your .venv (hundreds of MB), and your .env file full of secrets, and COPY . . would bake them all into the image.

A .dockerignore file uses .gitignore-style patterns to exclude paths from the context:

.dockerignore
.git.venv__pycache__/*.pyc.env.env.*tests/.pytest_cache/

Excluding junk also helps the cache: if .git were in the context, COPY . . would miss after every commit, even when no code changed.

Quick check
You forgot .dockerignore. Your Dockerfile has COPY . . and your project folder has a .env with a database password. You push the image to a public registry. What happened?
Need a nudge? A hint rules out a wrong answer.
Put it in order6 steps

Put this FastAPI Dockerfile in the order that caches best.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Practice

First, parse a Dockerfile the way Docker's frontend does. Then compute exactly which layers rebuild after a change.

ChallengeEasy

Parse a Dockerfile

Docker reads a Dockerfile one instruction per line. Write a function that turns the text of a Dockerfile into a list of [INSTRUCTION, arguments] pairs.

Rules:

  • Skip blank lines and comment lines (lines whose first non-space character is #).
  • The instruction is the first word, converted to uppercase (Docker accepts from as well as FROM).
  • The arguments are the rest of the line with surrounding spaces trimmed.
  • A line ending in a backslash \ continues on the next line. Drop the backslash, trim each piece, and join the pieces with a single space.
FROM python:3.13-slim
# install deps
RUN pip install \
    fastapi

becomes

[["FROM", "python:3.13-slim"], ["RUN", "pip install fastapi"]]
def parse_dockerfile(text: str) -> list[list[str]]: # Join continued lines first, then split each line into instruction + args. pass
ChallengeMedium

Which layers rebuild?

Docker caches each instruction as a layer. When you rebuild, a COPY step is a cache miss if any file it copies has changed. After the first miss, every later instruction rebuilds too, because each layer sits on top of the one before it.

Write a function that takes the list of Dockerfile instructions and the list of changed file paths and returns the 0-based indexes of the instructions that rebuild.

Rules:

  • Only COPY instructions look at files. Every other instruction is a cache hit unless an earlier one missed.
  • COPY a b c dest copies the sources a, b, c (every word except the last). There are no flags.
  • A source s matches a changed file f when s is ., or f == s, or f starts with s (without a trailing /) followed by /. So app/ and app both match app/main.py.
FROM python:3.13-slim                 0
WORKDIR /app                          1
COPY requirements.txt .               2
RUN pip install -r requirements.txt   3
COPY . .                              4
CMD ["fastapi", "run", "main.py"]     5
 
changed = ["main.py"]  →  [4, 5]
def rebuilt_layers(instructions: list[str], changed: list[str]) -> list[int]: # Find the first COPY that copies a changed file. Everything from there rebuilds. pass
Key terms
build context
The folder sent to the builder by docker build. COPY can only read files inside it.
.dockerignore
Patterns excluding files (like .git, .venv, .env) from the build context.
cache hit
Docker reuses a layer because the instruction, the parent layer, and any copied files are unchanged.
exec form
CMD ["prog", "arg"]: runs the program directly as PID 1 so it receives signals.
ENTRYPOINT vs CMD
ENTRYPOINT is the fixed program; CMD is the default arguments, replaced by anything passed to docker run.
ARG vs ENV
ARG exists only during the build; ENV is stored in the image and visible at runtime.