Lab: from a naive Dockerfile to a slim, non-root multi-stage image
Containerize a small FastAPI service twice: first with a naive Dockerfile whose size, leaked .env file, root user and slow shutdown you measure, then with a .dockerignore and a multi-stage Dockerfile that runs as a non-root user, reports its health and rebuilds in seconds after a code change. Finish by seeing how ENTRYPOINT and CMD combine and how docker run and Compose override each.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Write the service and run its test locally
- Step 2: Build a naive image and measure it
- Step 3: Shrink the build context with .dockerignore
- Step 4: Write the multi-stage Dockerfile
- Step 5: Check the user, the health check and shutdown
- Step 6: Prove the dependency layer survives a code change
- Step 7: ENTRYPOINT and CMD, and how to override them
- Troubleshooting
- Check your understanding
- Apply it: stretch task
- Review prompt
Lessons of Containerization
- A container is a process with boundaries Concept · 15 min
- Images, overlay layers, the build cache and what not to bake in Concept · 20 min
- Lab: from a naive Dockerfile to a slim, non-root multi-stage image Lab · 30 min
- Running containers deliberately: ports, volumes, bind mounts, devices and GPUs, environment and logs Worked example · 25 min
- Lab: an app and its database with Compose, health checks and a live-reload loop Lab · 30 min
- Check: debug three broken containers Knowledge check · 8 questions
What you will learn
- Write a multi-stage Dockerfile that yields a small image running as a non-root user, with cache-friendly layer order and a .dockerignore.
01. Goal and setup
You will package a small FastAPI notes API as a container image. First you write the Dockerfile most people write on their first day and measure what is wrong with it, then fix it step by step: a .dockerignore, a multi-stage build whose dependency layer survives code changes, a non-root user, a health check and an exec-form CMD. The result is about one seventh of the size and shuts down cleanly. Last, you see how ENTRYPOINT and CMD combine.
You need Docker Engine 23 or later (BuildKit is then the default builder) or a current Docker Desktop, and Python 3.10 or later on your machine for the local check. The lab was run with Docker Engine 29.8, Buildx 0.37, the python:3.12-slim image (Python 3.12.15 on Debian trixie), FastAPI 0.146 and uvicorn 0.54. Image IDs, sizes and timings will differ on your machine. Create this layout:
notes-api/
├── app/
│ ├── __init__.py (empty)
│ ├── healthcheck.py
│ └── main.py
├── tests/
│ └── test_health.py
├── .env
└── requirements.txt02. Step 1: Write the service and run its test locally
Pin the two direct dependencies. (A production project would also lock the transitive ones with a tool such as pip-compile or uv lock.)
fastapi==0.146.0
uvicorn[standard]==0.54.0The service stores notes as JSON lines in a file under NOTES_DATA_DIR. It touches that file at start-up, so a missing or read-only data directory stops the container at once instead of failing on the first request. Lesson 4 relies on that behaviour.
"""Notes API: a small FastAPI service used to practise containers."""
import os
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import FastAPI
from pydantic import BaseModel
DATA_DIR = Path(os.environ.get('NOTES_DATA_DIR', '/data'))
NOTES_FILE = DATA_DIR / 'notes.jsonl'
class Note(BaseModel):
title: str
body: str = ''
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
DATA_DIR.mkdir(parents=True, exist_ok=True)
NOTES_FILE.touch() # fail at startup, not on the first request
yield
app = FastAPI(title='Notes API', lifespan=lifespan)
@app.get('/health')
def health() -> dict[str, str]:
return {'status': 'ok', 'env': os.environ.get('APP_ENV', 'dev')}
@app.post('/notes', status_code=201)
def add_note(note: Note) -> Note:
with NOTES_FILE.open('a') as f:
f.write(note.model_dump_json() + '\n')
return note
@app.get('/notes')
def list_notes() -> list[Note]:
lines = NOTES_FILE.read_text().splitlines()
return [Note.model_validate_json(line) for line in lines]The slim base image has no curl, so the container's health probe is a few lines of Python that exit with status 0 when /health answers 200 and 1 otherwise:
"""Exit 0 when the API answers /health, so Docker can mark the container healthy."""
import sys
import urllib.request
URL = 'http://127.0.0.1:8000/health'
try:
with urllib.request.urlopen(URL, timeout=2) as response:
healthy = response.status == 200
except OSError: # refused, timed out, or an HTTP error status
healthy = False
sys.exit(0 if healthy else 1)from fastapi.testclient import TestClient
from app.main import app
def test_health(tmp_path, monkeypatch) -> None:
monkeypatch.setattr('app.main.DATA_DIR', tmp_path)
monkeypatch.setattr('app.main.NOTES_FILE', tmp_path / 'notes.jsonl')
with TestClient(app) as client:
assert client.get('/health').json()['status'] == 'ok'Now create the things a real project folder accumulates: a local virtual environment, test caches and a .env file with a (fake) token. They matter in step 3.
printf 'NOTES_API_TOKEN=dev-only-not-a-secret\n' > .env
python3 -m venv .venv
.venv/bin/pip install -q -r requirements.txt pytest httpx2
.venv/bin/python -m pytest -q. [100%]
1 passed in 0.78s03. Step 2: Build a naive image and measure it
Write the Dockerfile that many first attempts look like:
FROM python:3.12
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD uvicorn app.main:app --host 0.0.0.0 --port 8000docker build -f Dockerfile.naive -t notes-api:naive .
docker images notes-api
docker run --rm notes-api:naive sh -c 'whoami; ls -A /app; cat /app/.env'IMAGE ID DISK USAGE CONTENT SIZE EXTRA
notes-api:naive 67c085671198 1.77GB 457MB
root
.env
.pytest_cache
.venv
Dockerfile.naive
app
requirements.txt
tests
NOTES_API_TOKEN=dev-only-not-a-secretThe build also printed a warning, JSONArgsRecommended, about the last line. Count the problems:
- Size. 1.77 GB on disk and 457 MB to pull. The full
python:3.12image ships compilers and hundreds of Debian packages the service never uses, andCOPY . .added your 56 MB.venv, which was built for your machine and is useless inside the image. - A leaked secret.
.envis now in a layer. Anyone who can pull this image can read the token, and deleting it in a later step would not help. - Root. The service runs as root, which on a default engine is root on the host kernel (lesson 1).
- Cache order.
COPY . .comes beforepip install, so editing any file, even a test, reinstalls every dependency. In our run that step took about 20 seconds. - Shutdown. The shell form of
CMDruns the command through/bin/sh -c.
The last one is easy to miss, so measure it:
docker run -d --name naive notes-api:naive
docker exec naive ps -o pid,user,cmd
time docker stop naive
docker inspect --format '{{.State.ExitCode}}' naive
docker rm naive PID USER CMD
1 root /bin/sh -c uvicorn app.main:app --host 0.0.0.0 --port 8000
7 root /usr/local/bin/python3.12 /usr/local/bin/uvicorn app.main:app --h…
12 root ps -o pid,user,cmd
naive
real 0m10.288s
user 0m0.019s
sys 0m0.020s
137
naivedocker stop sends SIGTERM to PID 1, which here is the shell, not uvicorn. Linux drops a terminating signal sent to PID 1 of a PID namespace unless that process installed a handler for it; sh has none and would not forward it anyway. So nothing happens until Docker sends SIGKILL after 10 seconds: exit code 137, no graceful shutdown, requests in flight cut off. Every deploy and every restart pays those 10 seconds.
04. Step 3: Shrink the build context with .dockerignore
The build context is everything docker build can see in the folder you pass it. To see exactly what COPY . . receives, copy the context into a throwaway image and list it, skipping the inside of .venv to keep the listing short:
FROM alpine:3.24
COPY . /ctx
CMD ["sh", "-c", \
"du -sh /ctx | cut -f1; find /ctx -maxdepth 2 -not -path '/ctx/.venv/*' | sort"]docker build -q -f Dockerfile.ctx -t ctx-check . >/dev/null && docker run --rm ctx-check50.9M
/ctx
/ctx/.env
/ctx/.pytest_cache
/ctx/.pytest_cache/.gitignore
/ctx/.pytest_cache/CACHEDIR.TAG
/ctx/.pytest_cache/README.md
/ctx/.pytest_cache/v
/ctx/.venv
/ctx/Dockerfile.ctx
/ctx/Dockerfile.naive
/ctx/app
/ctx/app/__init__.py
/ctx/app/__pycache__
/ctx/app/healthcheck.py
/ctx/app/main.py
/ctx/requirements.txt
/ctx/tests
/ctx/tests/__pycache__
/ctx/tests/test_health.pyOnly app/ and requirements.txt belong in the image. Create a .dockerignore next to the Dockerfile. Its patterns are matched from the root of the context, so __pycache__ alone would only exclude a folder at the top level; **/ matches at any depth.
# Local environments, caches and version control
.git
.venv
**/__pycache__
**/*.py[co]
.pytest_cache
# Secrets and machine-specific settings
.env
.env.*
# Not needed inside the image
tests/
Dockerfile*
compose*.yamldocker build -q -f Dockerfile.ctx -t ctx-check . >/dev/null && docker run --rm ctx-check
docker rmi ctx-check24.0K
/ctx
/ctx/.dockerignore
/ctx/app
/ctx/app/__init__.py
/ctx/app/healthcheck.py
/ctx/app/main.py
/ctx/requirements.txt
Untagged: ctx-check:latest
Deleted: sha256:cf4592039b01adcf6b77bae806c0cc06c7541fa3fd0f9db3cd20094b942a8bb5From 51 MB to 24 KB. BuildKit still reads Dockerfile.ctx although the pattern Dockerfile* excludes it: the Dockerfile is sent separately from the context. The .env file is gone from the context, so no COPY can leak it again, and edits to tests or local caches no longer change the checksum of COPY . ..
05. Step 4: Write the multi-stage Dockerfile
Create Dockerfile (no suffix) in notes-api/:
# syntax=docker/dockerfile:1
# ---- Stage 1: install dependencies into a virtual environment ----
FROM python:3.12-slim AS builder
ENV PIP_DISABLE_PIP_VERSION_CHECK=1
RUN python -m venv /opt/venv
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip \
/opt/venv/bin/pip install -r requirements.txt
# ---- Stage 2: the runtime image ----
FROM python:3.12-slim AS runtime
ENV PATH="/opt/venv/bin:$PATH" \
PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
NOTES_DATA_DIR=/data
RUN groupadd --system --gid 10001 app \
&& useradd --system --uid 10001 --gid app --no-create-home app \
&& mkdir /data && chown app:app /data
WORKDIR /app
COPY --from=builder /opt/venv /opt/venv
COPY app/ ./app/
USER app
EXPOSE 8000
HEALTHCHECK --interval=10s --timeout=3s --start-period=10s --retries=3 \
CMD ["python", "-m", "app.healthcheck"]
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]Read it from the top:
# syntax=docker/dockerfile:1asks BuildKit for the latest stable Dockerfile syntax, which the--mountoptions need on older engines.- The builder stage creates a virtual environment in
/opt/venvand installs onlyrequirements.txtinto it. Because that file is copied alone, the slow install step is reused until the requirements change. The cache mount keeps pip's downloads between builds without putting them in a layer. - The runtime stage starts again from a clean
python:3.12-slimand copies just the finished/opt/venvacross. Both stages use the same base image, so the interpreter path the venv points at exists in both. Anything else the builder touched, including the pip cache and any compilers you might install there later, stays behind. PYTHONDONTWRITEBYTECODEstops Python writing.pycfiles at run time, andPYTHONUNBUFFEREDsends log lines out immediately sodocker logsshows them.groupaddanduseraddcreate a system user with a fixed UID and GID, 10001, and give it/data. The code in/appstays owned by root, so the service can read its code but not change it.USER appmakes every later step and the container itself run as that user.HEALTHCHECKrunspython -m app.healthcheckinside the container every 10 seconds, as the same user and in the same working directory as the app. Three failures in a row mark the container unhealthy;--start-periodgives the app 10 seconds before failures count.- The exec form of
CMD(a JSON array) makes uvicorn PID 1 itself, so it receivesSIGTERMdirectly. That works because uvicorn handlesSIGTERM; a PID 1 without a handler ignores it like the shell did, so add one or run withdocker run --init(Compose:init: true), which puts tini at PID 1 to forward signals.
Build it:
docker build -t notes-api:slim .
docker images notes-apiIMAGE ID DISK USAGE CONTENT SIZE EXTRA
notes-api:naive 67c085671198 1.77GB 457MB
notes-api:slim bfcc5ae07928 252MB 59.7MBFrom 1.77 GB to 252 MB on disk, and from 457 MB to 60 MB per pull. Most of what remains is the slim base itself (about 45 MB compressed); the dependencies add about 14 MB.
06. Step 5: Check the user, the health check and shutdown
docker run --rm notes-api:slim sh -c 'id; ls -A /app; ls -ld /data'
docker run -d --name notes -p 127.0.0.1:8000:8000 notes-api:slim
docker ps --filter name=notes --format '{{.Names}} {{.Status}}'
sleep 12
docker ps --filter name=notes --format '{{.Names}} {{.Status}}'
curl -s 127.0.0.1:8000/health; echouid=10001(app) gid=10001(app) groups=10001(app)
app
drwxr-xr-x 2 app app 4096 Oct 19 07:26 /data
27c15cc92748a04dc698cf6bb717df8833375b57a17553ca3ad0ed6d778c98cd
notes Up Less than a second (health: starting)
notes Up 12 seconds (healthy)
{"status":"ok","env":"dev"}The process runs as app, the image contains only app/, and the health status moved from starting to healthy after the first successful probe. The port is published on 127.0.0.1 only, as in lessons 1 and 4. Now stop it and compare with the naive image:
time docker stop notes
docker inspect --format '{{.State.ExitCode}}' notes
docker logs notes
docker rm notesnotes
real 0m3.936s
user 0m0.032s
sys 0m0.021s
0
INFO: Started server process [1]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO: 127.0.0.1:36128 - "GET /health HTTP/1.1" 200 OK
INFO: 172.17.0.1:35404 - "GET /health HTTP/1.1" 200 OK
INFO: Shutting down
INFO: Waiting for application shutdown.
INFO: Application shutdown complete.
INFO: Finished server process [1]
notesExit code 0 and a clean shutdown sequence in the log, well inside the 10-second grace period (most of the few seconds docker stop took was Docker's own clean-up on our busy host). The first /health request came from 127.0.0.1: that is the health check probe, running inside the container. The second came through the published port from the Docker bridge gateway, 172.17.0.1.
07. Step 6: Prove the dependency layer survives a code change
Edit the docstring on the first line of app/main.py (any change will do), then rebuild and keep only the step names and cache hits from the plain progress output:
docker build --progress=plain -t notes-api:slim . 2>&1 \
| grep -E '^#[0-9]+ (\[(builder|runtime)|CACHED)' | cut -c1-60#3 CACHED
#7 [builder 1/4] FROM docker.io/library/python:3.12-slim@sha
#8 [builder 4/4] RUN --mount=type=cache,target=/root/.cache/
#8 CACHED
#9 [builder 3/4] COPY requirements.txt .
#9 CACHED
#10 [runtime 2/5] RUN groupadd --system --gid 10001 app &&
#10 CACHED
#11 [runtime 3/5] WORKDIR /app
#11 CACHED
#12 [builder 2/4] RUN python -m venv /opt/venv
#12 CACHED
#13 [runtime 4/5] COPY --from=builder /opt/venv /opt/venv
#13 CACHED
#14 [runtime 5/5] COPY app/ ./app/Every step is CACHED except the last COPY (#3 is the Dockerfile syntax image from the first line), and the whole build took about 3 seconds in our run. With the naive Dockerfile the same edit reran pip install. If you change requirements.txt instead, the install step reruns but the cache mount means pip downloads only what is new.
08. Step 7: ENTRYPOINT and CMD, and how to override them
Your Dockerfile sets only CMD. Many images also set ENTRYPOINT, which fixes the executable, while CMD supplies its default arguments. docker run IMAGE args replaces all of CMD; --entrypoint replaces ENTRYPOINT.
This probe on the alpine:3.24 image from step 3 has ENTRYPOINT ["echo", "uvicorn"], so it prints the command line that a real uvicorn image would run:
FROM alpine:3.24
# A probe: echo prints the command line instead of starting a server.
ENTRYPOINT ["echo", "uvicorn"]
CMD ["app.main:app", "--host", "0.0.0.0", "--port", "8000"]docker build -q -f Dockerfile.entry -t entry-demo . >/dev/null
docker inspect --format '{{json .Config.Entrypoint}} {{json .Config.Cmd}}' entry-demo
docker run --rm entry-demo
docker run --rm entry-demo --reload
docker run --rm entry-demo app.main:app --host 0.0.0.0 --reload
docker run --rm --entrypoint whoami entry-demo["echo","uvicorn"] ["app.main:app","--host","0.0.0.0","--port","8000"]
uvicorn app.main:app --host 0.0.0.0 --port 8000
uvicorn --reload
uvicorn app.main:app --host 0.0.0.0 --reload
rootThe first line is the config stored in the image. With no arguments, Docker ran ENTRYPOINT plus CMD. --reload replaced all of CMD, so a real uvicorn image would stop with Error: Missing argument 'APP'; to add a flag, repeat the defaults you still need, as the next command does. --entrypoint whoami replaced the executable and dropped CMD too. Now the shell form and Compose:
FROM alpine:3.24
ENTRYPOINT echo uvicorn
CMD ["app.main:app", "--host", "0.0.0.0", "--port", "8000"]services:
dev:
image: entry-demo
command: ["app.main:app", "--host", "0.0.0.0", "--reload"] # replaces CMD
other-tool:
image: entry-demo
entrypoint: ["echo", "python", "-m", "uvicorn"] # replaces ENTRYPOINT, drops CMDdocker build -q -f Dockerfile.entry-shell -t entry-shell . >/dev/null
docker run --rm entry-shell --reload
docker compose -f compose.entry.yaml run --rm dev
docker compose -f compose.entry.yaml run --rm other-tool
docker compose -f compose.entry.yaml down
docker rmi entry-demo entry-shelluvicorn
uvicorn app.main:app --host 0.0.0.0 --reload
python -m uvicornThe shell form runs /bin/sh -c 'echo uvicorn', ignoring CMD and --reload, and like a shell-form CMD it keeps SIGTERM from your process (step 2), so write both instructions in exec form. Compose follows the same rules: command: replaces CMD, and a non-null entrypoint: replaces ENTRYPOINT and ignores the image's CMD. That is why the development override in lesson 5 writes the whole uvicorn command in command:: this lab's image has no ENTRYPOINT. Also note that setting ENTRYPOINT resets a CMD inherited from the base image.
A tool image, such as a linter, suits ENTRYPOINT ["tool"] with CMD ["--help"]; a service image like notes-api:slim is fine with CMD alone, which keeps docker run --rm -it notes-api:slim sh simple for debugging.
09. Troubleshooting
10. Check your understanding
11. Apply it: stretch task
Bring your practice project to the same standard, then go one step further:
- Write its
.dockerignoreand multi-stage Dockerfile, with a non-root user with a fixed UID, an exec-formCMDand aHEALTHCHECKthat hits a real readiness route. - Agree a size budget, for example 300 MB on disk, and add a check your CI can run after the build:
docker image inspect --format '{{.Size}}' notes-api:slimprints the uncompressed size in bytes; fail the job when it is over the budget. - If a dependency needs a compiler, install
build-essentialin the builder stage only and confirm withdocker historythat the runtime image did not grow. - Run
docker build --check .and fix anything it reports. It runs the same build checks that produced theJSONArgsRecommendedwarning, without building.
12. Review prompt
Without looking back, write the multi-stage Dockerfile for this service from memory: both stages, the order of the COPY steps, the user creation, USER, HEALTHCHECK and an exec-form CMD. Next to each line, write one sentence on what would go wrong without it. Then list five entries for a Python project's .dockerignore and say which of them protects a secret. Finally, explain what docker run IMAGE --reload runs when the image has ENTRYPOINT ["uvicorn"] and a CMD, and how to override the entry point.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.