Docker for ML
Lesson opener
In one line: Containerizing the FastAPI churn serving app.
Why it matters: Containers eliminate environment drift between train-time pins and serve-time pins.
Before this lesson: Serving with FastAPI / Docker Desktop install
Before you start
| Resource | Link |
|---|---|
| Previous | Serving with FastAPI |
| Next | MLflow tracking |
| Prerequisites | Serving with FastAPI, Docker Desktop install |
| Time | ~50 minutes |
What you will learn
- Containerizing the FastAPI churn serving app
- Multi-stage Docker builds to keep images small
- Why layer order matters for CI cache hits
- Validating Dockerfile tokens and cache keys in Python offline
- Pinning Python packages inside the image via
docs/mlops/requirements.txt
Why containerize the serving app
"Works on my laptop" is the enemy. A Docker image packages the app, the Python environment, and the model into one artifact that runs identically in local Docker Desktop, staging, and a free host. For Indian hybrid teams — laptop in Pune, host in Singapore — the container is the contract.
WHY Containers eliminate environment drift between train-time pins and serve-time pins.
WHEN Every deployment past “demo on localhost,” including free-tier demos for stakeholder week.
Pin note: install the course pins inside the image from docs/mlops/requirements.txt (scikit-learn==1.5.2, fastapi==0.115.5, uvicorn==0.32.1, pydantic==2.10.2, joblib==1.4.2, and the rest). Official docs: Docker multi-stage builds.
WHY multi-stage for ML APIs
ML images bloat fast: compilers, caches, and unused build wheels. A multi-stage build keeps a fat builder stage and a slim runtime stage. The runtime copies installed packages only — not pip’s build debris.
WHEN single-stage is enough: Local learning and throwaway prototypes. Prefer multi-stage as soon as you push to a registry or a free host with image-size limits.
Failure modes that look like “Docker is broken”
| Failure | Symptom | Fix |
|---|---|---|
COPY . . before requirements | Every code edit reinstalls sklearn | Copy requirements.txt first |
| Model missing in image | /predict 500; /health may still look ok | Bake or mount the pickle; set MODEL_PATH |
| Wrong working directory | joblib.load path errors | Set WORKDIR /app and use paths relative to it |
Binding 127.0.0.1 only | Host curl cannot reach container | uvicorn --host 0.0.0.0 |
| Unpinned base tag drift | Silent dependency change on rebuild | Pin base (python:3.12-slim) and pip packages |
Indian workplace framing: a retention engineer in Hyderabad and a platform engineer in Noida should be able to run the same docker run -p 8000:8000 churn-api and hit the same /health JSON. If they cannot, the image is not the contract yet — stop debating metrics and fix packaging.
Multi-stage Dockerfile
# Stage 1: build
FROM python:3.12-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir --user -r requirements.txt
# Stage 2: runtime
FROM python:3.12-slim
WORKDIR /app
COPY --from=builder /root/.local /root/.local
COPY . .
ENV PATH=/root/.local/bin:$PATH
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]# requires: server
docker build -t churn-api .
docker run -p 8000:8000 churn-api
curl http://localhost:8000/health[!important] The second stage copies only the installed packages and code — no build tools, no source maps.
Offline practices: validate Dockerfile text in Python
You can unit-test Dockerfile conventions without building an image. That keeps CI fast when Docker is unavailable.
Runnable: required Dockerfile tokens
DOCKERFILE = """
FROM python:3.12-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir --user -r requirements.txt
FROM python:3.12-slim
WORKDIR /app
COPY --from=builder /root/.local /root/.local
COPY . .
ENV PATH=/root/.local/bin:$PATH
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
""".strip()
required_tokens = [
"FROM python:3.12-slim",
"COPY requirements.txt",
"--no-cache-dir",
"COPY --from=builder",
"ENV PATH",
"uvicorn",
]
missing = [t for t in required_tokens if t not in DOCKERFILE]
assert not missing, missing
stages = DOCKERFILE.count("FROM ")
assert stages >= 2, "expected multi-stage build"
print(f"Dockerfile OK: {stages} stages, {len(required_tokens)} tokens present")Runnable: layer cache key hash
Docker rebuilds a layer when its inputs change. Sketch a cache key from the requirements pin text — same idea as "hash of requirements.txt decides whether pip install is cached":
import hashlib
requirements = """
scikit-learn==1.5.2
pandas==2.2.3
numpy==2.1.3
joblib==1.4.2
fastapi==0.115.5
uvicorn==0.32.1
pydantic==2.10.2
mlflow==2.18.0
scipy==1.14.1
""".strip()
def layer_cache_key(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()[:12]
key_a = layer_cache_key(requirements)
key_b = layer_cache_key(requirements)
key_c = layer_cache_key(requirements + "\n# comment only still changes bytes\n")
assert key_a == key_b
assert key_a != key_c
print("cache key stable:", key_a)
print("changed pins invalidate:", key_c)Runnable: ENV PATH join (runtime stage idea)
def join_path(*parts: str) -> str:
"""Join PATH-like entries the way Docker ENV PATH=a:b does on Linux."""
cleaned = [p for p in parts if p]
return ":".join(cleaned)
path = join_path("/root/.local/bin", "/usr/local/bin", "/usr/bin")
assert path.startswith("/root/.local/bin:")
assert "uvicorn" not in path # PATH holds dirs, not binaries
print("PATH=", path)Understanding image layers (size sketch)
Each COPY and RUN creates a layer. Layers are cached: if requirements.txt has not changed, pip install uses the cached layer. That is why we COPY requirements.txt . before COPY . ..
Rough size sketch for teaching (numbers are illustrative, not a measurement of your machine):
| Layer | Typical MB (sketch) | Invalidated when |
|---|---|---|
Base python:3.12-slim | ~120 | Base tag changes |
pip install -r requirements.txt | ~200–400 | Pins change |
App COPY . . | ~5–50 | Source or model changes |
Copying the model pickle in the final COPY . . means every model bump rebuilds only the thin app layer if requirements are unchanged — that is the CI win.
WHEN to invalidate on purpose
Bump pins deliberately when you accept a new sklearn behaviour, not because someone ran pip install -U on a laptop. After a pin bump, rebuild, re-run round-trip predict checks, and only then retag :latest for the free host.
WHY cache keys matter in Indian CI: Shared runners and spotty bandwidth make full sklearn reinstalls painful. Stable requirements text keeps morning pipelines under the timebox before the stand-up.
Churn capacity and image promotion
The weekly 50-call list depends on the model bytes inside the image. Promote images the same way you promote runs: tag with git SHA or run id (churn-api:abc1234), keep :prev for rollback, and never overwrite an untagged blob that ops already scored against. Packaging discipline is part of retention reliability — not a side quest for DevOps alone.
WHEN the thin app layer still feels heavy: Large pickles and bundled sample CSVs inflate the final COPY . .. Keep training data out of the serve image; mount or fetch only the model artifact the API needs. Retention demos in Bengaluru fail more often from a missing pickle path than from a missing forest algorithm — fix packaging before you retune hyperparameters.
Runnable: decide whether a pin bump invalidates the pip layer
# Offline demo: detect whether requirements text changed enough to bust cache
def pins_changed(old: str, new: str) -> bool:
return old.strip() != new.strip()
old = "scikit-learn==1.5.2\nfastapi==0.115.5\n"
new_same = "scikit-learn==1.5.2\nfastapi==0.115.5\n"
new_bump = "scikit-learn==1.5.2\nfastapi==0.115.6\n"
assert pins_changed(old, new_same) is False
assert pins_changed(old, new_bump) is True
print("pin bump invalidates pip layer:", pins_changed(old, new_bump))Runnable: image tag helper for rollback (:prev)
# Offline demo: build promote/rollback tags for a churn API image
def tags(name: str, sha: str) -> dict[str, str]:
short = sha[:7]
return {
"immutable": f"{name}:{short}",
"latest": f"{name}:latest",
"prev": f"{name}:prev",
}
t = tags("churn-api", "abc1234deadbeef")
assert t["immutable"] == "churn-api:abc1234"
assert t["prev"].endswith(":prev")
print(t)# Keep training CSVs out of the serve image
models/*.pkl
!models/.gitkeep
data/Verified against scikit-learn 1.5.2, pandas 2.2.3, numpy 2.1.3 (+6 more) documentation, September 2026.
Test yourself
- What is the benefit of a multi-stage Docker build?
- Why do we copy
requirements.txtbefore the rest of the code? - What does
COPY --from=builderdo? - What command builds a Docker image?
- What flag maps port 8000 on the host to port 8000 in the container?
- Why is
--no-cache-dirused in the Dockerfile? - What is a Docker image layer?
- Name one thing that would invalidate the cached
pip installlayer. - What does
ENV PATH=/root/.local/bin:$PATHdo? - True or false: the runtime stage should include build tools.