Concept Explanation
"It works on my machine" is a statement about your machine, not your code. Your laptop has Python 3.12, a particular libssl, an environment variable you set six months ago and forgot, and a Postgres client installed by Homebrew. The server has none of that.
A Docker image is your application plus every dependency down to the operating system libraries, frozen into one file. A container is a running instance of that image. The image that passed your tests is byte-for-byte the image that runs in production — the class of bug where staging and production differ simply stops existing.
The Vocabulary
| Term | Meaning |
|---|---|
| Dockerfile | The recipe: instructions for building an image |
| Image | The built artifact — read-only, versioned, shareable |
| Container | A running instance of an image |
| Layer | One instruction's output; cached and reused across builds |
| Registry | Where images are stored (Docker Hub, ECR, GHCR) |
| Volume | Storage that survives the container being deleted |
The Layer Cache Is Everything
Every instruction creates a layer. Docker reuses cached layers until something changes — and once one layer is invalidated, every layer after it rebuilds. This single fact determines how you order a Dockerfile.
# WRONG: any source change reinstalls every dependency (2+ minutes)
COPY . .
RUN pip install -r requirements.txt
# RIGHT: dependencies only reinstall when requirements.txt changes (2 seconds)
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
Copy the thing that rarely changes first. That ordering is the difference between a 3-second rebuild and a 3-minute one, every single time you edit a file.
Choosing a Base Image
| Base | Size | Notes |
|---|---|---|
python:3.12 | ~1 GB | Full Debian; rarely necessary |
python:3.12-slim | ~150 MB | The sensible default |
python:3.12-alpine | ~50 MB | musl libc — many wheels do not exist, so builds compile from source and get slower |
Alpine looks appealing and usually is not. Packages like numpy, pandas, and psycopg ship prebuilt manylinux wheels that do not work on musl, so Alpine forces a source compile that takes minutes and needs a toolchain. Use slim.
Always pin the version. FROM python:3 means your build changes underneath you when a new release lands.
The Instructions You Need
| Instruction | Purpose |
|---|---|
FROM | Base image |
WORKDIR | Set (and create) the working directory |
COPY | Copy files from build context into the image |
RUN | Execute a command at build time |
ENV | Set an environment variable |
EXPOSE | Document the port (does not publish it) |
USER | Switch away from root |
CMD | Default command at run time — overridable |
ENTRYPOINT | The command that always runs |
HEALTHCHECK | How Docker tests whether the container is alive |
RUN happens once during build; CMD happens each time a container starts. Confusing them is the most common Dockerfile error.
Multi-Stage Builds
Compilers, headers, and build tools are needed to build but not to run. A multi-stage build compiles in one image and copies only the results into a clean final image:
FROM python:3.12-slim AS builder
# ... install build-essential, compile wheels ...
FROM python:3.12-slim
COPY --from=builder /opt/venv /opt/venv
This routinely cuts an 800 MB image to 180 MB, which means faster pulls, faster deploys, and a smaller attack surface.
.dockerignore
Without it, COPY . . sends your .git directory, .venv, __pycache__, and every dataset in the folder to the daemon — slow builds and secrets baked into layers.
.git
.venv
__pycache__/
*.pyc
.env
.pytest_cache
data/
The Two Environment Variables
ENV PYTHONUNBUFFERED=1 # logs appear immediately, not on buffer flush
ENV PYTHONDONTWRITEBYTECODE=1 # no .pyc files cluttering the image
PYTHONUNBUFFERED is the one people discover the hard way, after an hour of wondering why docker logs shows nothing while the app is clearly running.
Code Example #1 (Basic)
A working Dockerfile for a FastAPI service, with the reasoning inline.
# ---------- Dockerfile ----------
FROM python:3.12-slim
# Logs stream immediately; no .pyc files written into the image
ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
PIP_NO_CACHE_DIR=1 \
PIP_DISABLE_PIP_VERSION_CHECK=1
WORKDIR /app
# Dependencies FIRST -- this layer is cached until requirements.txt changes
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Source code LAST -- editing a .py file only invalidates from here down
COPY . .
# Never run as root: if the app is compromised, the blast radius is smaller
RUN useradd --create-home --shell /bin/bash appuser \
&& chown -R appuser:appuser /app
USER appuser
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"
# Exec form (a JSON array), not shell form -- so the process receives SIGTERM
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
# ---------- main.py ----------
import os
from fastapi import FastAPI
app = FastAPI(title="Dockerised Service")
@app.get("/health")
def health():
return {"status": "ok"}
@app.get("/")
def root():
return {
"message": "Running inside a container",
"env": os.getenv("APP_ENV", "development"),
"hostname": os.uname().nodename, # the container id
}
# Build, tag, and run
docker build -t myservice:1.0.0 .
docker run -p 8000:8000 -e APP_ENV=production myservice:1.0.0
# Useful while developing
docker ps # what is running
docker logs -f <container_id> # follow the logs
docker exec -it <id> bash # shell inside a running container
docker image ls # check how big your image got
Two details that matter more than they look. --host 0.0.0.0 is mandatory — bind to 127.0.0.1 inside a container and it is unreachable from outside, which is the single most common "my container starts but I get connection refused" cause. And the exec-form CMD means uvicorn is PID 1 and receives SIGTERM directly, so docker stop shuts down gracefully instead of hard-killing after ten seconds.
Code Example #2 (Intermediate)
Multi-stage build plus Compose with a real database.
# ---------- Dockerfile (multi-stage) ----------
# =============== STAGE 1: build ===============
FROM python:3.12-slim AS builder
ENV PIP_NO_CACHE_DIR=1 PIP_DISABLE_PIP_VERSION_CHECK=1
# Compilers needed only to BUILD wheels -- they never reach the final image
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential gcc libpq-dev \
&& rm -rf /var/lib/apt/lists/*
# A virtualenv makes the artifact one directory that is trivial to copy
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# =============== STAGE 2: runtime ===============
FROM python:3.12-slim
ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
PATH="/opt/venv/bin:$PATH"
# Only the RUNTIME library, not the -dev headers or the compiler
RUN apt-get update && apt-get install -y --no-install-recommends \
libpq5 curl \
&& rm -rf /var/lib/apt/lists/* \
&& useradd --create-home --uid 10001 appuser
# The entire dependency tree, in one layer, with no build toolchain
COPY --from=builder /opt/venv /opt/venv
WORKDIR /app
COPY --chown=appuser:appuser . .
USER appuser
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD curl -fsS http://localhost:8000/health || exit 1
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "2"]
# ---------- compose.yaml ----------
services:
api:
build: .
ports:
- "8000:8000"
environment:
DATABASE_URL: postgresql://app:secret@db:5432/appdb # 'db' = the service name
APP_ENV: development
depends_on:
db:
condition: service_healthy # wait for READY, not merely started
develop:
watch:
- action: sync # live-reload source without rebuilding
path: ./app
target: /app/app
- action: rebuild
path: requirements.txt # dependency change -> full rebuild
db:
image: postgres:16-alpine
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: secret
POSTGRES_DB: appdb
volumes:
- pgdata:/var/lib/postgresql/data # survives 'docker compose down'
healthcheck:
test: ["CMD-SHELL", "pg_isready -U app -d appdb"]
interval: 5s
timeout: 3s
retries: 10
volumes:
pgdata:
# ---------- main.py: reading config from the environment ----------
import os
from contextlib import asynccontextmanager
from fastapi import FastAPI
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
database_url: str # no default: fail loudly if unset
app_env: str = "development"
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
settings = Settings()
@asynccontextmanager
async def lifespan(app: FastAPI):
print(f"starting in {settings.app_env}")
# open connection pools here
yield
print("shutting down cleanly") # runs on SIGTERM
# close pools here
app = FastAPI(lifespan=lifespan)
@app.get("/health")
def health():
return {"status": "ok"}
@app.get("/config")
def config():
host = settings.database_url.split("@")[-1] # never log credentials
return {"env": settings.app_env, "db_host": host}
docker compose up --build # build and start everything
docker compose watch # live-reload development mode
docker compose logs -f api # follow one service
docker compose down # stop (volumes survive)
docker compose down -v # stop AND delete the database volume
docker image ls | grep myservice # compare single-stage vs multi-stage size
Three things make this production-shaped rather than a toy. condition: service_healthy means the API waits for Postgres to actually accept connections instead of racing it — depends_on alone only waits for the process to start. The named pgdata volume means your data survives docker compose down, which is what separates a volume from a container's own filesystem. And DATABASE_URL arriving as an environment variable rather than a hardcoded string is what lets the identical image run in development, staging, and production.
Common Mistakes
COPY . .beforepip install: every source edit reinstalls every dependency. Copyrequirements.txtfirst.- Binding to
127.0.0.1: unreachable from outside the container. Always--host 0.0.0.0. - No
.dockerignore:.git,.venv, and datasets get sent to the daemon and sometimes baked into layers. - Secrets in the Dockerfile:
ENV API_KEY=sk-live-...is permanently visible indocker history, even if a later layer removes it. Pass secrets at runtime. - Running as root: the default. One
useraddandUSERline removes a whole category of container escapes. - Shell-form
CMD:CMD uvicorn main:appwraps the process in/bin/sh, which swallowsSIGTERM, sodocker stophard-kills after 10 seconds. Use the JSON array form. - Unpinned base images:
FROM python:3silently changes version between builds. - Choosing Alpine for a data-science image: no manylinux wheels, so builds compile from source and take ten times longer.
- Storing data inside the container: it vanishes when the container is removed. Use a volume.
depends_onwithout a healthcheck condition: your app starts before Postgres is accepting connections and crashes on the first query.- Forgetting
PYTHONUNBUFFERED=1:docker logsshows nothing until the buffer flushes, which looks exactly like a hung app. - Separate
RUN apt-get updateandRUN apt-get install: the cached update layer means you install stale package lists. Chain them with&&.
Best Practices
- Order the Dockerfile least-changing to most-changing: base, system packages, dependencies, then source.
- Use
python:3.12-slimand pin the minor version. - Write
.dockerignorebefore your first build. - Use multi-stage builds to keep compilers out of the runtime image.
- Run as a non-root user with an explicit UID.
- Use exec-form
CMDso signals reach your process and shutdown is graceful. - Set
PYTHONUNBUFFERED=1andPYTHONDONTWRITEBYTECODE=1in every Python image. - Inject configuration through environment variables, and read it with
BaseSettingsso a missing value fails at startup. - Add a
HEALTHCHECKso orchestrators can tell "running" from "working". - Use named volumes for state, never the container filesystem.
- Tag images with a version, not just
latest—latestmakes rollbacks ambiguous. - Chain
apt-get update && apt-get installin oneRUNand clean/var/lib/apt/listsin the same layer. - Check
docker image lsafter building. If it is over 500 MB for a web service, something is being copied that should not be.
Practice Exercises
- The Cache Test: Write a Dockerfile with
COPY . .beforepip install, time a rebuild after editing one source file, then reorder it correctly and time it again. Report both numbers. - The Slimming Exercise: Take a single-stage Dockerfile for an app needing
gccat build time, convert it to multi-stage, and comparedocker image lssizes before and after. - The Compose Stack: Write a
compose.yamlwith an API service and a Postgres service, using a healthcheck pluscondition: service_healthy, a named volume, and the database URL passed as an environment variable. Confirm data survivesdocker compose downand disappears afterdown -v.