Docker Images for Models
The Docker course showed how images package any app. Models add a twist: a saved model is fussy about its environment. A churn model pickled with one version of scikit-learn may refuse to load, or quietly behave differently, under another. The image is how you freeze the environment the model was trained for.
The rule
Pin the environment, bake in a known model, tag it with the version.
Here is a serving image for the churn API:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY serve.py .
COPY model/ ./model/
EXPOSE 8000
CMD ["uvicorn", "serve:app", "--host", "0.0.0.0", "--port", "8000"]And requirements.txt, with exact versions matching the training run:
scikit-learn==1.5.2
pandas==2.2.3
fastapi==0.115.0
uvicorn==0.30.6The three parts of the rule:
- Pin. A specific base tag (
python:3.11-slim, notlatest) and==versions for every library, matching training. Unpinned installs pick up whatever is newest on build day. - Bake in a known model.
model/is filled by a build step that fetches a named version from the registry, never whatever file is lying around. Some teams instead load the model at startup from the registry; either way, the version is explicit. - Tag. Build as
churn-api:7when it contains model version 7. The image tag and the model version now tell the same story.
Layer order matters for speed: copying requirements.txt and installing before copying the code means a code change does not reinstall every library. Models that need GPUs start from a CUDA-enabled base image instead, which is much larger, so only use one when the model needs it.