Learning path: Serve a Model in Production: Docker, Latency and Scaling · Step 5 of 9
Containerising a Model API: A Dockerfile for FastAPI and scikit-learn, Line by Line
Read a 16-line Dockerfile for a FastAPI model API: what .dockerignore leaves out, why packages go before code, why 0.0.0.0 matters, where 671MB really goes, and how a health check watches the app.
What you will learn
- Shrink the build context with a .dockerignore file
- Order Dockerfile steps so a code change reuses the cached package layer
- Explain why uvicorn must listen on 0.0.0.0 inside a container
- Find where an ML image's size really goes and add a HEALTHCHECK
Before you start
- Docker Essentials for ML
- Deploy a Machine Learning Model with FastAPI
In Docker Essentials we built an image of the rain API and ran it, but the Dockerfile was a recipe somebody handed us. Now we read all 16 lines ourselves, see where the image size really goes, and check that the app inside is actually working.
The project: app.py, model.joblib, requirements.txt, a Dockerfile and a .dockerignore file, plus client.py, test_app.py, requirements-dev.txt and a README.md.
Packing a lunchbox
Think about packing a lunchbox yourself instead of buying one ready-made:
- Leave out what the meal doesn't need.
- Mind the order. What rarely changes goes in first, at the bottom, so swapping tomorrow's sandwich doesn't mean unpacking everything.
- Stick a label on the lid saying what's inside. The label doesn't open anything.
- Keep one note outside the box, saying which sauce today, so you can change it without repacking.
Leave things out, mind the order, label the lid, keep one setting outside. That's the whole Dockerfile.
The whole Dockerfile
FROM python:3.13-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py model.joblib ./
ENV MODEL_PATH=/app/model.joblib
HEALTHCHECK --interval=10s --timeout=3s \
CMD python -c "import urllib.request as u; \
u.urlopen('http://127.0.0.1:8000/health')"
EXPOSE 8000
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", \
"--port", "8000"]
Leave things out: .dockerignore
When you build, Docker gathers the folder it's pointed at and sends it to the builder. That's the build context. The .dockerignore file lists what to leave out:
.venv
__pycache__
*.pyc
mlruns
*.egg-info
.pytest_cache
test_app.py
client.py
requirements-dev.txt
README.md
Without it, the context was 9 files and 6,990 bytes. With it, 5 files and 5,740 bytes. Honestly, that's a small saving in a project this size. The real win is that test code stays out, and a heavy virtual environment (.venv) would stay out too. And from those five files, only three go into the image: app.py, model.joblib and requirements.txt.
The bottom of the box: packages before code
FROM python:3.13-slimis the bottom layer: a small Linux system with Python already in it.WORKDIR /app: everything after this happens in that folder.COPY requirements.txt .thenRUN pip install ...: the packages land as their own layer. That step took about 159 seconds on this machine.
The order is on purpose. Docker reuses any layer whose inputs haven't changed. Because the packages are installed before our code is copied, editing app.py doesn't re-run the install. We changed one comment in app.py and built again (log trimmed to the steps):
#6 [3/5] COPY requirements.txt .
#6 CACHED
#7 [2/5] WORKDIR /app
#7 CACHED
#8 [4/5] RUN pip install --no-cache-dir -r requirements.txt
#8 CACHED
#9 [5/5] COPY app.py model.joblib ./
#9 DONE 0.4s
Three steps say CACHED, only the copy ran, and the whole rebuild took 2.5 seconds instead of minutes.
The top of the box
COPY app.py model.joblib ./: the model travels inside the image.ENV MODEL_PATH=/app/model.joblib: the default path, which we can change from outside.EXPOSE 8000is the label on the lid. It's only a note; it doesn't open anything. You still need-pwhen you run.CMDstarts uvicorn with--host 0.0.0.0.
Why 0.0.0.0 and not 127.0.0.1
This one trips up a lot of people. Inside a container, 127.0.0.1 means the container itself, so a request from outside never reaches it. We tried it: started the container with --host 127.0.0.1, mapped a port, and called it from our machine.
curl: (52) Empty reply from server
0.0.0.0 listens on every network interface, and the log confirms it:
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
The same curl now gets an answer:
{"status":"ok","model":"model.joblib"}
Where the size really goes
The image is 671MB. The model file is 4,298 bytes, about 4 KB, so it barely shows up.
The weight is the base image and the packages. We asked for seven packages, and pip installed 24. The biggest single download was scipy, at 35.3 MB, and we never asked for it by name; scikit-learn needs it. Those download sizes are compressed, so they don't add up to 671MB.
So for a small model like ours, baking it into the image is fine. A model measured in gigabytes is a different call. You'd usually keep it outside the image and share it with -v, so a new model doesn't mean a new image.
Running doesn't mean working: HEALTHCHECK
A running container isn't always a working one, so Docker can keep asking for you. Every 10 seconds, with a 3 second timeout, Docker runs a tiny Python command inside the container that calls /health. Here's that route in app.py:
@app.get("/health")
def health():
name = os.path.basename(MODEL_PATH)
return {"status": "ok", "model": name}
What we saw after docker run:
- Right after the start, the status said
starting. - At 2.6 seconds the app was answering, and
client.pygot 200, Yes, 0.63. - At about 8.5 seconds the status flipped to
healthy.
rain Up 12 seconds (healthy)
You can spot the probe in docker logs, coming from inside the container:
INFO: 127.0.0.1:46630 - "GET /health HTTP/1.1" 200 OK
And because /health returns the model's file name, it also tells you which model is loaded.
Change the setting, not the image
The last piece is the note outside the box. In app.py, the model path comes from the environment and falls back to model.joblib:
MODEL_PATH = os.environ.get("MODEL_PATH", "model.joblib")
app = FastAPI(title="Rain Predictor")
model = joblib.load(MODEL_PATH) # fails fast
So -e MODEL_PATH=/models/rain_v2.joblib (with the folder shared by -v, as in Docker Essentials) swaps the model with no rebuild. Point it at a file that isn't there, and the container stops:
docker run --name bad -e MODEL_PATH=/models/missing.joblib rain-api
FileNotFoundError: [Errno 2] No such file or directory: '/models/missing.joblib'
Exit code 1. And that's a good thing: a loud stop beats a server running with no model.
Common mistakes
- Copying the code before installing packages. Every code edit then re-runs the slow pip install.
- Starting uvicorn on 127.0.0.1 inside the container. Outside callers get an empty reply.
- Thinking
EXPOSEpublishes a port. It's a label.-pdoes the publishing. - No
.dockerignore. Tests, notebooks or a whole.venvend up in the build context. - Baking a huge model into the image. Every new model becomes a new multi-gigabyte image. Mount it instead.
Quick recap
| Idea | Line | Real result |
|---|---|---|
| Leave things out | .dockerignore | 9 files to 5; 3 go into the image |
| Mind the order | packages before COPY app.py | rebuild after an edit: 2.5 s |
| Let requests in | --host 0.0.0.0 | 127.0.0.1 gave "Empty reply from server" |
| Size | FROM + pip install | 671MB image, 4 KB model |
| Keep watching | HEALTHCHECK | starting, then healthy at about 8.5 s |
| One setting outside | ENV MODEL_PATH + -e | swap the model, no rebuild |
Try it yourself
Build the image, change one line in app.py, and build again. Watch which steps run and which ones say CACHED.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Docker Essentials for ML: Images, Containers and Volumes with a Model API
Next →Latency Math: p50, p95, p99 and Why the Tail Reaches Your Users
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.