Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 30 min · revision 3

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

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:

Folder layout
notes-api/
├── app/
│   ├── __init__.py      (empty)
│   ├── healthcheck.py
│   └── main.py
├── tests/
│   └── test_health.py
├── .env
└── requirements.txt

02. 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.)

requirements.txt
fastapi==0.146.0
uvicorn[standard]==0.54.0

The 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.

app/main.py
"""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:

app/healthcheck.py
"""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)
tests/test_health.py
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.

Terminal, in notes-api/
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
Expected output (the time differs)
.                                                                        [100%]
1 passed in 0.78s

03. Step 2: Build a naive image and measure it

Write the Dockerfile that many first attempts look like:

Dockerfile.naive
FROM python:3.12
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD uvicorn app.main:app --host 0.0.0.0 --port 8000
Terminal
docker 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'
Expected output after the build log (the first build pulls about 450 MB; ID and sizes vary)
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-secret

The build also printed a warning, JSONArgsRecommended, about the last line. Count the problems:

  1. Size. 1.77 GB on disk and 457 MB to pull. The full python:3.12 image ships compilers and hundreds of Debian packages the service never uses, and COPY . . added your 56 MB .venv, which was built for your machine and is useless inside the image.
  2. A leaked secret. .env is now in a layer. Anyone who can pull this image can read the token, and deleting it in a later step would not help.
  3. Root. The service runs as root, which on a default engine is root on the host kernel (lesson 1).
  4. Cache order. COPY . . comes before pip install, so editing any file, even a test, reinstalls every dependency. In our run that step took about 20 seconds.
  5. Shutdown. The shell form of CMD runs the command through /bin/sh -c.

The last one is easy to miss, so measure it:

Terminal
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
Expected output (after the container ID; the long line is cut short with …)
    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
naive

docker 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:

Dockerfile.ctx
FROM alpine:3.24
COPY . /ctx
CMD ["sh", "-c", \
     "du -sh /ctx | cut -f1; find /ctx -maxdepth 2 -not -path '/ctx/.venv/*' | sort"]
Terminal
docker build -q -f Dockerfile.ctx -t ctx-check . >/dev/null && docker run --rm ctx-check
Expected output (the size depends on your .venv)
50.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.py

Only 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.

.dockerignore
# 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*.yaml
Terminal
docker build -q -f Dockerfile.ctx -t ctx-check . >/dev/null && docker run --rm ctx-check
docker rmi ctx-check
Expected output (the image ID differs)
24.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:cf4592039b01adcf6b77bae806c0cc06c7541fa3fd0f9db3cd20094b942a8bb5

From 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/:

Dockerfile
# 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:1 asks BuildKit for the latest stable Dockerfile syntax, which the --mount options need on older engines.
  • The builder stage creates a virtual environment in /opt/venv and installs only requirements.txt into 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-slim and copies just the finished /opt/venv across. 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.
  • PYTHONDONTWRITEBYTECODE stops Python writing .pyc files at run time, and PYTHONUNBUFFERED sends log lines out immediately so docker logs shows them.
  • groupadd and useradd create a system user with a fixed UID and GID, 10001, and give it /data. The code in /app stays owned by root, so the service can read its code but not change it.
  • USER app makes every later step and the container itself run as that user.
  • HEALTHCHECK runs python -m app.healthcheck inside 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-period gives the app 10 seconds before failures count.
  • The exec form of CMD (a JSON array) makes uvicorn PID 1 itself, so it receives SIGTERM directly. That works because uvicorn handles SIGTERM; a PID 1 without a handler ignores it like the shell did, so add one or run with docker run --init (Compose: init: true), which puts tini at PID 1 to forward signals.

Build it:

Terminal
docker build -t notes-api:slim .
docker images notes-api
Expected output after the build log (IDs and sizes vary a little)
IMAGE             ID             DISK USAGE   CONTENT SIZE   EXTRA
notes-api:naive   67c085671198       1.77GB          457MB
notes-api:slim    bfcc5ae07928        252MB         59.7MB

From 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

Terminal
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; echo
Expected output (the date and the container ID differ)
uid=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:

Terminal
time docker stop notes
docker inspect --format '{{.State.ExitCode}}' notes
docker logs notes
docker rm notes
Expected output (timings and ports vary)
notes

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]
notes

Exit 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:

Terminal
docker build --progress=plain -t notes-api:slim . 2>&1 \
  | grep -E '^#[0-9]+ (\[(builder|runtime)|CACHED)' | cut -c1-60
Expected output (step numbers and order vary: BuildKit works on both stages in parallel)
#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:

Dockerfile.entry
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"]
Terminal, in notes-api/
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
Expected output
["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
root

The 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:

Dockerfile.entry-shell
FROM alpine:3.24
ENTRYPOINT echo uvicorn
CMD ["app.main:app", "--host", "0.0.0.0", "--port", "8000"]
compose.entry.yaml
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 CMD
Terminal
docker 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-shell
Expected output (Compose's progress lines and the output of docker rmi are left out)
uvicorn
uvicorn app.main:app --host 0.0.0.0 --reload
python -m uvicorn

The 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

Practice check · 3 questions

Check your Dockerfile choices

Questions about the two images you built.

Q1. With CMD uvicorn app.main:app --host 0.0.0.0 (shell form), docker stop takes 10 seconds and the exit code is 137. Why?
Q2. A .dockerignore containing the line __pycache__ still lets app/__pycache__ into the build context. Which line fixes that?
Q3. Why does the Dockerfile create the user with a fixed UID (10001) instead of letting useradd pick one?
Practice only: not graded, not saved, not evidence.

11. Apply it: stretch task

Bring your practice project to the same standard, then go one step further:

  1. Write its .dockerignore and multi-stage Dockerfile, with a non-root user with a fixed UID, an exec-form CMD and a HEALTHCHECK that hits a real readiness route.
  2. 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:slim prints the uncompressed size in bytes; fail the job when it is over the budget.
  3. If a dependency needs a compiler, install build-essential in the builder stage only and confirm with docker history that the runtime image did not grow.
  4. Run docker build --check . and fix anything it reports. It runs the same build checks that produced the JSONArgsRecommended warning, 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.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check