Docker — containers
Be able to package an application in a container and run it reproducibly.
Prerequisites
Intuition
A container packages the application together with everything it needs — libraries, system packages, the Python version — so that it runs the same way everywhere. «It works on my machine» stops being a problem.
| Concept | Means |
|---|---|
| Image | the recipe, built once, immutable |
| Container | a running instance of an image |
| Layer | every instruction in the Dockerfile becomes a cached layer |
| Volume | a folder shared with the host that outlives the container |
The layer caching governs the build time. If a line changes, that line and everything after it is rebuilt. Hence: copy requirements.txt and install before you copy the code — then the dependencies are cached and the rebuild takes seconds instead of minutes.
Code
FROM python:3.12-slim
# 1. System packages (rarely change)
RUN apt-get update && apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
# 2. Dependencies BEFORE the code — this layer is cached when only the code changes
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# 3. The code last
COPY src/ ./src/
# 4. Do not run as root
RUN useradd -r -u 10001 appuser && chown -R appuser /app
USER appuser
ENV PYTHONUNBUFFERED=1
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s CMD curl -fsS http://localhost:8000/healthz || exit 1
CMD ["python", "-m", "uvicorn", "src.app:app", "--host", "0.0.0.0", "--port", "8000"]
docker build -t myapp:1.0 .
docker run --rm -p 8000:8000 \
-e LLM_API_KEY="$LLM_API_KEY" \ # secrets via the environment, never in the image
-v "$PWD/data:/app/data:ro" \ # data as a volume, not baked in
--memory 2g --cpus 2 \
myapp:1.0
Four common errors: secrets baked into the image (they stay in the layers), latest as a tag (not reproducible), running as root, and copying the whole directory first so that the cache never hits. A .dockerignore with .git, .venv and data/ often saves hundreds of megabytes.
Mastery means
- Packages an application in a container
- Writes a Dockerfile with layer caching
- Runs reproducibly with volumes and environment variables
Sign in to do the exercises and build your mastery up.
Sources
- Docker — dokumentation (Apache-2.0) — Apache-2.0
- OWASP — Docker Security Cheat Sheet — CC BY-SA 4.0