Day 5: Package it with Docker

Python Backend Basics: Build the ShopStream API ~5 min read 30 min hands-on

Shrink a 1.7 GB root image to 236 MB with a multi-stage, non-root Dockerfile, a health check and config that fails fast.

"It works on my machine" usually means three things: a different Python, a package version nobody pinned, and a setting that only exists on one laptop. Containers fix the first two. Today you fix the third too, and you learn what a Dockerfile costs: the version most people write first produces a 1.7 GB image that runs as root. The one you build today is 236 MB, runs as an unprivileged user, reports its own health, and refuses to start with a clear message when its configuration is wrong.

What you build

A three-stage Dockerfile:

Plus:

  • requirements.txt (runtime, pinned) and requirements-dev.txt (adds pytest, httpx, coverage).

  • .dockerignore so .git, caches and .env never enter an image.

  • app/check_config.py: runs before the server. No DATABASE_URL β†’ exit 2 with one line. Database unreachable after 15 tries β†’ exit 3 with a hint.

  • Compose uses target: runtime for the API and target: dev for the tools container, and gives Postgres a named volume so data survives docker compose down.

What we measured

The image is 7Γ— smaller: the slim base drops compilers and docs you never use at runtime, and the multi-stage build leaves pip's leftovers and the test tools behind. Smaller images pull faster on every deploy and contain fewer packages that can have vulnerabilities. Verify checks that pytest isn't in the runtime image at all.

Start-up is about 1.3 seconds slower. That second is check_config connecting to the database before the web server starts β€” a trade we choose on purpose, because the alternative is a container that starts "fine" and fails on its first request.

"Works on my machine", the same image started three ways:

Read the full lesson free

This lesson is one of the first 3 in its course, free with an account β€” the full article, implementation guide and scripts. No card needed.

Already a member? Sign in