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.
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/
- 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, ...
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.
FROM python:3.13-slim
WORKDIR /appWORKDIR 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.
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.
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:
ARGis a build-time variable. You can override it withdocker build --build-arg PYTHON_VERSION=3.14 .. It does not exist when the container runs.ENVsets an environment variable that is baked into the image and present at runtime.PYTHONUNBUFFERED=1makesprintand logs appear immediately indocker logs.USER appusermakes 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 8000is documentation: it records which port the app listens on. It does not publish the port to your machine. You do that with-pat run time (next lesson).CMDis the default command the container runs. Note--host 0.0.0.0: inside a container,127.0.0.1means "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 each instruction to what it does.
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.
First build: everything runs. The pip install layer takes most of the time.
First build: same as before.
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.
Press Run (⌘ Enter) to see what happens.app/main.py and rebuild. Which instructions actually run?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?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 | |
|---|---|---|
| Syntax | CMD ["uvicorn", "app.main:app"] | CMD uvicorn app.main:app |
| What runs | uvicorn directly, as PID 1 | /bin/sh -c "uvicorn ...", sh is PID 1 |
Gets SIGTERM on docker stop? | Yes | No, sh does not forward it |
Variable expansion like $PORT | No | Yes |
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:
ENTRYPOINTis the fixed program. Arguments after the image name indocker runare appended to it.CMDis the default arguments (or the default command if there is noENTRYPOINT). Arguments after the image name replace it.
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
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:
.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.
.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?Put this FastAPI Dockerfile in the order that caches best.
- Tap the steps below in the right order.
Practice
First, parse a Dockerfile the way Docker's frontend does. Then compute exactly which layers rebuild after a change.
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
fromas well asFROM). - 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 \
fastapibecomes
[["FROM", "python:3.13-slim"], ["RUN", "pip install fastapi"]]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
COPYinstructions look at files. Every other instruction is a cache hit unless an earlier one missed. COPY a b c destcopies the sourcesa,b,c(every word except the last). There are no flags.- A source
smatches a changed filefwhensis., orf == s, orfstarts withs(without a trailing/) followed by/. Soapp/andappboth matchapp/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]- build context
- The folder sent to the builder by
docker build.COPYcan 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.