Sub topic 9
Packaging the service in a container
A container image bundles your code, the model file, and the exact Python packages into one unit. The same image runs on your laptop, in CI, and on a server. This chapter builds an image for the iris service, runs it, and covers the mistakes that most often break model containers.
This chapter assumes you have the main.py and model.joblib files from the earlier chapters, and that Docker is installed. You should be comfortable with a Dockerfile at the level of FROM, COPY, and RUN.
Why a model service needs a container
A model service depends on more than your source code. The pickled model file only loads correctly with a compatible scikit-learn version. Pickle-based formats such as joblib do not guarantee compatibility across versions, so loading a file with a different version can warn, fail, or return different results. A container fixes the whole environment: the OS libraries, the Python version, and the package versions. The model and the code that loads it then ship together.
A container also gives you one thing a scaling system can start, stop, and replace. Later chapters on health checks and scaling rely on that.
Pin the dependencies
Create requirements.txt from the environment where you trained the model. The scikit-learn version must match the one that wrote model.joblib.
pip freeze | grep -iE '^(scikit-learn|joblib|fastapi|uvicorn|pydantic)==' > requirements.txt
cat requirements.txtThe file should list those five packages with exact == versions. Commit it. If you retrain the model with a newer scikit-learn, regenerate this file and rebuild the image in the same step.
The Dockerfile
This Dockerfile builds on the slim Python image, installs dependencies, copies the app and model, and starts Uvicorn.
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY main.py model.joblib ./
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]Each line has a purpose:
FROM python:3.11-slimis a small Debian-based image with Python. Use the Python minor version you trained with, to avoid surprises.WORKDIR /appsets the directory for the following commands. The service loadsmodel.joblibby relative path, so the working directory must be where the file lives.COPY requirements.txt .followed byRUN pip installcomes before the code copy on purpose. See the next section.--no-cache-dirstops pip from storing downloaded wheels in the image, which keeps it smaller.EXPOSE 8000documents the port. It does not publish it.CMDuses the list (exec) form, so Uvicorn is the main process and receives stop signals directly.
Layer caching
Docker builds an image as a stack of layers, one per instruction. If an instruction and its inputs have not changed, Docker reuses the cached layer. When one layer changes, every layer after it is rebuilt.
Dependencies change rarely and code changes often. Copying requirements.txt first means that editing main.py only rebuilds the last COPY layer. The slow pip install layer stays cached.
Keep the build context clean
docker build . sends the whole directory, called the build context, to the Docker daemon. If your project folder holds a virtual environment, datasets, or notebooks, the build gets slow and you risk copying files you did not intend. Add a .dockerignore file next to the Dockerfile:
.venv/
__pycache__/
*.pyc
.git/
data/
notebooks/
tests/The Dockerfile above copies only two files by name, so ignored files will not end up in the image. The .dockerignore file still speeds up the build and prevents accidents if someone later changes COPY to COPY . ..
Build and run
docker build -t iris-service:1.0 .
docker run --rm -p 8000:8000 iris-service:1.0-t names and tags the image. -p 8000:8000 publishes container port 8000 on host port 8000. Without -p, the service runs but nothing outside the container can reach it.
In another terminal, check the health endpoint and then request a prediction:
curl http://localhost:8000/health
curl -X POST http://localhost:8000/predict \
-H "Content-Type: application/json" \
-d '{"sepal_length": 5.1, "sepal_width": 3.5, "petal_length": 1.4, "petal_width": 0.2}'The health response should show "model_loaded": true. The prediction should return a JSON object with a class_index. For these iris measurements the model should return 0, the setosa class.
Common failures
| Symptom | Likely cause | Fix |
|---|---|---|
| `curl` gets "connection reset" or "connection refused", but logs show Uvicorn started | Uvicorn bound to `127.0.0.1` inside the container | Pass `--host 0.0.0.0` in `CMD` |
| `curl` cannot connect, and `docker ps` shows no port mapping | Port not published | Add `-p 8000:8000` to `docker run` |
| Build fails at `COPY model.joblib` | Model file not in the build context or listed in `.dockerignore` | Run the training script first and check the ignore rules |
| Container exits at startup with `FileNotFoundError` | The working directory differs from the model path | Keep `WORKDIR /app` and the model in that directory |
| Warning about unpickling from a different scikit-learn version | Image has different package versions from training | Pin versions in `requirements.txt` and rebuild |
Run as a non-root user
By default, processes in a container run as root. A service that accepts input from the network should not. Add a user before CMD:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY main.py model.joblib ./
RUN useradd --create-home appuser
USER appuser
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]The service only reads model.joblib, so it needs no write permission to /app. The files copied by COPY are owned by root and readable by all users, which is enough.
Add a container health check
The /health endpoint is more useful once Docker can call it. The slim image has no curl, so use Python, which is already installed. Add this line before CMD:
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health', timeout=2)"urlopen raises an exception on a non-2xx status, so the command exits non-zero and Docker marks the container unhealthy. --start-period gives the service time to load the model before failures count. Orchestrators such as Kubernetes ignore the Dockerfile HEALTHCHECK and use their own probe settings. They call the same /health endpoint.
Design choices
Model inside the image or mounted at runtime. Baking model.joblib into the image, as above, makes each image tag a self-contained, reproducible release. The cost is a rebuild for every new model. Mounting the model from a volume or downloading it from object storage at startup lets you update the model without rebuilding, but the running version is then harder to trace, and startup depends on the storage being available. For a small model, baking it in is the simpler default.
Image size. python:3.11-slim with scikit-learn is a few hundred megabytes. Large images pull slowly when a new replica starts. Avoid installing the training stack (notebooks, plotting libraries) in the serving image. Keep a separate requirements file for training.
Worker processes. CMD starts one Uvicorn process. To use several CPU cores you can run more replicas of the container or add workers. Each process loads its own copy of the model into memory, so check the memory limit on the container. The scaling chapter returns to this.
Exercises
Exercise
You edit one line in main.py and rebuild. The build is fast and the pip install step shows as cached. Which Dockerfile ordering made that possible, and what would happen if the Dockerfile used COPY . . before RUN pip install -r requirements.txt?
Show answer
The Dockerfile copies requirements.txt and installs packages before it copies main.py. The pip install layer depends only on requirements.txt, so it is reused when main.py changes. With COPY . . first, any code edit changes that layer, which invalidates every later layer, so pip would reinstall all packages on each rebuild.
Exercise
The container logs show "Uvicorn running on http://127.0.0.1:8000", yet curl http://localhost:8000/health from the host fails even though you ran with -p 8000:8000. What is wrong, and what is the fix?
Show answer
Uvicorn is bound to 127.0.0.1, which inside the container is reachable only from within that container. Start it with --host 0.0.0.0 (as in the CMD line) so it listens on all interfaces and the published port can reach it.
Exercise
You retrain the model after upgrading scikit-learn locally, then rebuild the image without touching requirements.txt, which pins the older version. What risk does this create, and how do you avoid it?
Show answer
The model file was written by the newer scikit-learn, but the image installs the older one. Loading can emit warnings, raise an error, or give wrong predictions, because pickle-based model files are not guaranteed to be compatible across versions. Regenerate requirements.txt from the training environment so both use the same version, then rebuild the image.