Docker for Machine Learning: A Beginner’s Guide with Example
On this page
Short answer: Docker packages your machine learning model, code, Python version and libraries into a single image that runs the same way on your laptop, a teammate’s machine or a cloud server. For ML, you typically write a Dockerfile that installs dependencies, copies your trained model and API code (for example FastAPI), then docker build the image and docker run it as a container. This removes the “works on my machine” problem and is the standard first step towards deploying models in production.
Key takeaways
- An image is the packaged blueprint; a container is a running instance of it.
- Docker makes ML environments reproducible and portable.
- A basic ML Dockerfile has: base image → dependencies → code + model → start command.
- Keep images small, pin library versions and never bake secrets into images.
Why do data scientists need Docker?
- Reproducibility: the same Python and library versions everywhere
- Deployment: cloud services and Kubernetes run containers
- Collaboration: teammates run your project with one command
- Isolation: different projects can use different library versions without conflicts
Docker is a core stage of the MLOps roadmap.
Key Docker concepts
| Concept | Meaning |
|---|---|
| Dockerfile | Text file with instructions to build an image |
| Image | Read-only package of OS layer, runtime, libraries, code |
| Container | A running instance of an image |
| Registry | Stores images (Docker Hub, Amazon ECR and others) |
| Volume | Persistent storage outside the container |
| Port mapping | Exposes a container port on the host, e.g. -p 8000:8000 |
Example: containerise a scikit-learn model with FastAPI
Project structure
ml-api/
├── app.py
├── model.joblib
├── requirements.txt
└── Dockerfile
app.py
from fastapi import FastAPI
from pydantic import BaseModel
import joblib
app = FastAPI()
model = joblib.load('model.joblib')
class Features(BaseModel):
values: list[float]
@app.post('/predict')
def predict(features: Features):
pred = model.predict([features.values])
return {'prediction': pred.tolist()}
requirements.txt (pin versions)
fastapi==0.115.0
uvicorn==0.30.6
scikit-learn==1.5.2
joblib==1.4.2
Use the same scikit-learn version you trained with, otherwise loading the saved model can fail or behave differently.
Dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py model.joblib ./
EXPOSE 8000
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
Build and run
docker build -t ml-api:1.0 .
docker run -p 8000:8000 ml-api:1.0
# test
curl -X POST http://localhost:8000/predict \
-H 'Content-Type: application/json' \
-d '{"values": [5.1, 3.5, 1.4, 0.2]}'
Best practices for ML Docker images
- Use slim base images such as
python:3.11-slim - Copy requirements first so Docker caches the dependency layer
- Add a .dockerignore for datasets, notebooks, .git and virtual environments
- Don’t store large datasets in the image; mount volumes or read from cloud storage
- Never bake API keys into images; pass them as environment variables or secrets
- Tag images with versions (
ml-api:1.0), not onlylatest - Run as a non-root user in production
Docker Compose for multi-service ML apps
When your app needs more than one service (an API, a database, a vector store or MLflow), Docker Compose defines and starts them together with docker compose up. This is common for RAG applications that combine an API with a vector database.
Docker and GPUs
For deep learning, containers can use NVIDIA GPUs when the host has NVIDIA drivers and the NVIDIA Container Toolkit installed. Start from a CUDA-enabled base image (or an official PyTorch/TensorFlow GPU image) and run with --gpus all.
Common mistakes
- Unpinned library versions that change between builds
- Huge images from copying datasets and notebooks
- Binding the server to
127.0.0.1instead of0.0.0.0inside the container - Forgetting port mapping with
-p - Training inside the serving image instead of loading a saved model
Frequently asked questions
Is Docker required for data science jobs?
Not for every role, but it is expected for ML engineering and MLOps roles and is a strong plus for data scientists who deploy models.
What is the difference between Docker and a virtual environment?
A virtual environment isolates Python packages only; Docker isolates the whole runtime, including OS libraries and system dependencies.
Docker vs Kubernetes?
Docker builds and runs containers; Kubernetes orchestrates many containers across machines (scaling, restarts, rolling updates). Learn Docker first.
Where do I deploy a Docker ML API?
Options include cloud container services and Kubernetes. See how to deploy a machine learning model and AWS for data scientists.
Conclusion
Docker for machine learning means packaging your model, code and dependencies into one reproducible image. Start with a simple FastAPI + scikit-learn container, follow the best practices above, and you’ll have a deployable model and a valuable MLOps skill for your portfolio.
Learn deployment hands-on in our Machine Learning course.
Related reading
Learn with Mehul Prajapati in Borivali West
At Mehul Prajapati’s institute, you get 100% practical, hands-on training by industry experts with a minimum of 5+ years of experience, plus job-oriented programmes with placement support. Weekday and weekend batches are available, with multiple 2-hour slots between 8 am and 6 pm.
Address: 12th Floor, 1214, Gold Crest Business Centre, LT Rd, Above Westside Showroom, Borivali West, Mumbai, Maharashtra 400092
Call: +91 99301 12627 / +91 96645 45072
Visit the centre or call us to choose the right course and batch and to know the current fee structure.