Learning path: Serve a Model in Production: Docker, Latency and Scaling · Step 4 of 9
Docker Essentials for ML: Images, Containers and Volumes with a Model API
Pack the rain-prediction API into a Docker image, start a container from it, stop and remove it, and keep the model file outside the container with a volume. Every command and output comes from a real run.
What you will learn
- Explain the difference between a Dockerfile, an image, a container and a volume
- Build an image with docker build and start it with docker run -d -p
- Inspect, stop and remove a container while the image stays
- Share a model folder with a container using -v and point the app at it with -e
Before you start
- Deploy a Machine Learning Model with FastAPI
- Using a terminal
We have a small rain API: a FastAPI app with a saved scikit-learn model that answers one question, will it rain tomorrow? Right now it only runs on a machine where Python and the right packages are already set up. Move it to another machine and something is always missing.
Docker fixes that with three words: an image, a container and a volume. In this article we build one image, run it, stop it, and share a folder with it. If you haven't built the API yet, start with Deploy a Machine Learning Model with FastAPI.
Recipe, box, meal and fridge
Think about a meal kit.
- The recipe card says what goes in, and in what order. That's the Dockerfile.
- Follow it once and you get a sealed box with everything inside. That's the image, and it doesn't change.
- Open it and cook, and there's a meal on the table. That's a container, a running copy of the image. Here the meal kit falls short: a real box gets used up, but one image can start as many containers as you like.
- The fridge sits outside the box, and what's in it is still there after the table's been cleared. That's a volume.
Why bother with a box?
Let's see how much this app leans on its surroundings. Started with uvicorn on our machine, client.py gets an answer:
{'status': 'ok', 'model': 'model.joblib'}
200 {'rain_tomorrow': 'Yes', 'probability': 0.63}
Now the same code with the MODEL_PATH setting pointing at a file that isn't there:
FileNotFoundError: [Errno 2] No such file or directory: '/models/missing.joblib'
The server stops with exit code 1. So this app needs the right Python, seven pinned packages, a model file and a correct path. Miss one and it stops. An image carries all of them together, so another machine doesn't have to get them right.
The project folder holds app.py, model.joblib, requirements.txt, a Dockerfile, a .dockerignore, two helpers, client.py and test_app.py, plus requirements-dev.txt and a README.md. The Dockerfile is 16 lines; we read it line by line in Containerising a Model API. Here we just use it.
Build the image
docker build -t rain-api .
-t gives the image a name, and the dot says "use this folder". The build log (trimmed here to the step lines) shows five steps, and each one adds a layer:
#5 [1/5] FROM docker.io/library/python:3.13-slim@sha256:ae14d4ce...
#6 [2/5] WORKDIR /app
#7 [3/5] COPY requirements.txt .
#8 [4/5] RUN pip install --no-cache-dir -r requirements.txt
#8 DONE 159.4s
#9 [5/5] COPY app.py model.joblib ./
Step 1 pulls the base image, python:3.13-slim. We didn't have it, so Docker downloaded it. Steps 2 to 4 set a folder and install our packages, and that install is the slow part: about 159 seconds on this machine. Step 5 copies in the app and the model.
The whole build took about 220 seconds, and the image came out at 671MB. It's a stack of layers, and it doesn't change any more.
Start a container
An image just sits there until we start it:
docker run -d --name rain -p 8000:8000 rain-api
-dkeeps it running in the background.--name raingives the container a name we can use in later commands.-p 8000:8000joins port 8000 on our machine to port 8000 inside the container.
It prints one long container id, in under a second (0.9 s here). We're starting a process, not a whole new computer. About 2.6 seconds later the app is answering, and client.py gets exactly what it got before:
{'status': 'ok', 'model': 'model.joblib'}
200 {'rain_tomorrow': 'Yes', 'probability': 0.63}
Same code, same model, same answer. It's just packed in a box now.
Containers come and go
A few commands cover most of what you do with a running container.
docker ps --format "{{.Names}} {{.Status}}"
rain Up 12 seconds (healthy)
docker inspect --format '{{.State.Health.Status}}' rain
healthy
"Healthy" comes from a health check written into the Dockerfile; Containerising a Model API shows how it works.
docker logs rain shows what the app printed, including our predict request:
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO: 172.17.0.1:48848 - "GET /health HTTP/1.1" 200 OK
INFO: 172.17.0.1:48860 - "GET /health HTTP/1.1" 200 OK
INFO: 172.17.0.1:48864 - "POST /predict HTTP/1.1" 200 OK
Then stop it and remove it:
docker stop rain
docker rm rain
Here's the key part. The container is gone, and anything written inside it goes too. But the image is still there, untouched, ready to start the next one. In this run we started three containers from this one image. Containers come and go; the image stays.
Keep the data outside: volumes
So where do you keep a file that has to outlast a container? That's what a volume is for. Here's the run again, with two new flags:
docker run -d --name rain -p 8000:8000 -v ./models:/models -e MODEL_PATH=/models/rain_v2.joblib rain-api
-v ./models:/modelsshares themodelsfolder on our machine with the container, at/models. We put a copy of the model there, calledrain_v2.joblib.-e MODEL_PATH=...sets one environment variable, the model path, to that file.
{'status': 'ok', 'model': 'rain_v2.joblib'}
200 {'rain_tomorrow': 'Yes', 'probability': 0.63}
Same image, a different model file, no rebuild. (It's a copy of the same model, so the answer matches.)
Bind mount or named volume
To be exact, sharing a folder from your machine like this is called a bind mount. Docker can also manage a named volume for you:
docker volume create models
docker volume ls
DRIVER VOLUME NAME
local models
You use it with -v models:/models. We copied the model into it, and a brand-new container listing /models still saw the file:
rain_v2.joblib
Then docker volume rm models takes it away. Either way, the data lives outside the container, so removing the container doesn't touch it.
Common mistakes
- Forgetting
-p. The app runs inside the container, but nothing on your machine can reach it. - Saving files inside the container. They vanish with
docker rm. Anything that must survive goes in a volume. - Rebuilding to change a setting. If the app reads a setting from the environment, change it with
-einstead. - Mixing up image and container.
docker stopanddocker rmact on a container. The image is untouched.
Quick recap
| Word | Command | In this run |
|---|---|---|
| Image | docker build -t rain-api . | 5 steps, about 220 s, 671MB |
| Container | docker run -d --name rain -p 8000:8000 rain-api | answering after 2.6 s: Yes, 0.63 |
| Look inside | docker ps, inspect, logs | Up 12 seconds (healthy) |
| Clean up | docker stop rain, docker rm rain | container gone, image stays |
| Volume | -v ./models:/models -e MODEL_PATH=... | same image serves rain_v2.joblib |
Try it yourself
Build the image, start a container, and run client.py. Then stop it and remove it. Start it again from the same image, and check that you get the same answer.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Batch Scoring a Million Rows: Chunks, a Run ID and a Safe Rerun
Next →Containerising a Model API: A Dockerfile for FastAPI and scikit-learn, Line by Line
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.