Table of Contents
- Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama
- Why Docker Matters for Production MLOps
- Configuring Our Development Environment
- Project Structure
- Multi-Stage Docker Builds for Smaller ML Inference Images
- Docker Compose for ML Workflows
- GPU Support in Docker and Docker Compose
- How to Run Ollama in Docker for Local LLM Inference
- Docker Security Best Practices for Production ML Images
- How to Push ML Images to Docker Hub and GitHub Container Registry
- Production Checklist: Hardening Our ML Images
- Scaling ML Workloads Beyond Docker Compose with Swarm and Kubernetes
- Summary
Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama
In this lesson, we will learn advanced Docker techniques for MLOps. We will move beyond the basics of containers and Dockerfiles to explore how production-grade Machine Learning (ML) systems are built and deployed using Docker.
We will start by understanding why naïve Dockerfiles often fail in real-world ML pipelines and how multi-stage builds create leaner, faster, and more secure images. Then we will step into Docker Compose, the tool that lets us orchestrate multi-container ML workflows by connecting training jobs, inference application programming interfaces (APIs), databases, and caches in a single reproducible environment.
This lesson is the last in a 3-part series on Machine Learning Operations (MLOps):
- What Is MLOps? Architecture, MLOps vs DevOps, and LLMOps
- Getting Started with Docker for Machine Learning and MLOps
- Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama (this tutorial)
Since graphics processing units (GPUs) are at the heart of modern ML and deep learning, we will also learn how to run GPU-enabled containers using the NVIDIA Container Toolkit and configure GPU scheduling in Compose. We will also cover Docker for LLM workloads using Ollama. We will show how to containerize local large language models (LLMs) to ensure reproducibility and portability in the age of large language model operations (LLMOps).
Finally, we will discover production best practices for security and optimization, how to push images to cloud registries, and how to integrate Docker into continuous integration and continuous delivery (CI/CD) workflows. The lesson wraps up with a hands-on project: building a multi-stage ML inference service, orchestrating it with Compose, and proving it works seamlessly with GPU support.
By the end, we will have the skills to take Docker from a local ML convenience tool to a production-ready foundation for MLOps.
To learn how to build production-ready Docker images, orchestrate ML workflows with Compose, enable GPU support, and containerize LLM workloads, just keep reading.
Why Docker Matters for Production MLOps
Building our first ML Dockerfile is exciting, but it is only the beginning. The reality is that “toy” containers often fail when we try to scale them into production. They get too big, take forever to build, and may even contain hidden vulnerabilities. For MLOps engineers, these problems add friction in CI/CD pipelines and slow down deployments on Amazon Elastic Container Service (Amazon ECS), Kubernetes, or Lambda.

Common Problems with Naïve Dockerfiles
- Bloated Images: Beginners often use full Ubuntu or Anaconda images, which can easily exceed several gigabytes. This slows down pulls, pushes, and CI/CD builds.
- Rebuild Pain: If we copy our entire project before installing dependencies, every code change forces a full rebuild of the image.
- Security Risks: Running everything as root or leaving unnecessary packages installed makes containers vulnerable.
- Environment Drift: Training images and inference images often diverge, leading to “works in dev but not in prod” headaches.
These issues can make ML systems unreliable and expensive to operate. That is why we need to move from “it runs locally” to production-ready Docker.

Developer Productivity: Docker in VS Code and Dev Containers
In practice, most ML engineers spend their time inside Visual Studio Code (VS Code) or Jupyter. To make containerized workflows smoother, tools (e.g., VS Code Dev Containers) are now widely used. A .devcontainer.json file lets us define our development environment inside Docker, so we and our teammates can open VS Code and instantly get the same setup with all dependencies, extensions, and even GPU support preconfigured.
This approach ensures that the same container can be used for development, testing, and deployment, reducing environment drift. It also makes onboarding new collaborators trivial: instead of sharing a README with setup steps, we share a container definition.

Why This Matters for MLOps
MLOps is about reproducibility, collaboration, and reliable deployment. If our images are too heavy, insecure, or inconsistent, downstream processes such as CI/CD and monitoring become fragile. By learning multi-stage builds, Compose orchestration, GPU-ready containers, and registry integration, we will gain the tools to make Docker a true production backbone for ML.
In the next section, we will start with multi-stage builds to make ML Docker images lean, secure, and production-friendly.
Configuring Our Development Environment
To follow this Docker MLOps Production guide, we need Docker and supporting tools installed on our system.
Core Requirements
Docker Desktop (essential for all examples)
# Download from: https://www.docker.com/products/docker-desktop/ # Verify installation: $ docker --version $ docker compose version
Python 3.9+ (optional, for model customization)
# Verify Python installation $ python --version # Set up development environment $ python -m venv .venv $ source .venv/bin/activate # Windows: .venv\Scripts\activate # Install model creation dependencies $ pip install torch==2.1.0 torchvision==0.16.0 pytorch-lightning==2.1.0 scikit-learn==1.3.0
System Requirements
Memory and Storage
- 8 GB+ random-access memory (RAM) recommended (for LLM examples)
- 10 GB+ free disk space (for Docker images)
- solid-state drive (SSD) preferred for faster builds
Verify Docker Resources
# Check Docker system info $ docker system df $ docker info | grep -E 'CPUs|Total Memory'
GPU Support (Optional)
For accelerated training examples, install NVIDIA Container Toolkit:
Linux (Ubuntu/Debian)
$ curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg $ sudo apt-get update && sudo apt-get install -y nvidia-container-toolkit $ sudo systemctl restart docker
Test GPU access
$ docker run --gpus all nvidia/cuda:12.3.2-runtime-ubuntu22.04 nvidia-smi
Note: GPU examples will fall back to the central processing unit (CPU) if NVIDIA GPU is not available.
Validation
Quick Environment Check
# Test Docker functionality $ docker run hello-world # Verify Compose V2 $ docker compose version # Check available resources $ docker system info
Ready to start! All examples include pre-trained models and are ready to run immediately after environment setup.
Need Help Configuring Your Development Environment?

All that said, are you:
- Short on time?
- Learning on your employer’s administratively locked system?
- Wanting to skip the hassle of fighting with the command line, package managers, and virtual environments?
- Ready to run the code immediately on your Windows, macOS, or Linux system?
Then join PyImageSearch University today!
Gain access to Jupyter Notebooks for this tutorial and other PyImageSearch guides pre-configured to run on Google Colab’s ecosystem right in your web browser! No installation required.
And best of all, these Jupyter Notebooks will run on Windows, macOS, and Linux!
Project Structure
We first need to review our project directory structure.
Start by accessing this lesson’s “Downloads” section to retrieve the source code and example images.
From there, take a look at the directory structure:
docker-mlops-production/ ├── create_test_model.py # Creates real MNIST model (96.7% accuracy) ├── requirements.txt # Dependencies for model creation ├── multi-stage-example/ │ ├── train.py # PyTorch Lightning training script │ ├── inference.py # FastAPI inference service │ ├── requirements-train.txt # Training dependencies (heavy) │ ├── requirements-infer.txt # Inference dependencies (minimal) │ ├── Dockerfile # Multi-stage: training → inference │ └── README.md # Usage instructions ├── compose-basic/ │ ├── trainer/ │ │ ├── train.py # Model training script │ │ ├── Dockerfile │ │ └── requirements.txt │ ├── api/ │ │ ├── inference.py # Basic FastAPI service │ │ ├── Dockerfile │ │ └── requirements.txt │ ├── artifacts/ │ │ └── model.pth # Pre-trained MNIST model │ ├── docker-compose.yml # Trainer + API orchestration │ └── test.json # Sample test data ├── compose-extended/ │ ├── trainer/ # Same training setup │ │ ├── train.py │ │ ├── Dockerfile │ │ └── requirements.txt │ ├── api/ │ │ ├── inference.py # Enhanced with Redis + Postgres │ │ ├── Dockerfile │ │ └── requirements.txt # + redis, psycopg2-binary │ ├── artifacts/ │ │ └── model.pth # Pre-trained MNIST model │ └── docker-compose.yml # + Redis + Postgres services ├── gpu-examples/ │ ├── train_gpu.py # GPU-aware training script │ ├── Dockerfile.gpu-trainer # CUDA runtime base image │ ├── requirements-gpu.txt # PyTorch with CUDA support │ ├── docker-compose-gpu.yml # GPU scheduling examples │ └── README.md # GPU setup guide ├── ollama-llm/ │ ├── api/ │ │ ├── main.py # LLM API wrapper │ │ ├── Dockerfile │ │ └── requirements.txt # FastAPI + requests │ ├── docker-compose.yml # GPU version with Ollama │ ├── docker-compose-cpu.yml # CPU version for testing │ └── README.md # LLM model management ├── production-hardened/ │ ├── api.py # Security-hardened FastAPI │ ├── Dockerfile # Multi-stage + non-root user │ ├── requirements.txt │ ├── security-scan.sh # Vulnerability scanning script │ ├── SECURITY.md # Security best practices │ └── artifacts/ │ ├── .gitkeep │ └── model.pth # Pre-trained MNIST model └── README.md # Complete tutorial guide
Let us break down each folder:
multi-stage-example/
Demonstrates multi-stage Docker builds for lean ML images. Uses real PyTorch Lightning MNIST model (96.7% accuracy). Separates training (2.5 GB) from inference (800 MB) stages, achieving 3x size reduction for production deployment.
compose-basic/
Introduces Docker Compose orchestration through a workflow with a trainer service and an API service. Features real model artifacts shared via volumes, service dependencies with depends_on, and tested API endpoints for predictions.
compose-extended/
Adds production infrastructure with Redis caching and PostgreSQL logging. Includes real-world features such as cache hit tracking, prediction analytics via the /stats endpoint, and a multi-service architecture validated through testing.
gpu-examples/
Covers GPU acceleration using NVIDIA Container Toolkit. Includes Compute Unified Device Architecture (CUDA) runtime images, GPU scheduling in Compose, and CPU fallback configurations. Structure verified on both GPU and non-GPU systems.
ollama-llm/
Shows Large Language Model containerization with official Ollama Docker image (ollama/ollama:latest). Features both GPU and CPU configurations, FastAPI wrapper with health checks, and tested model management via representational state transfer (REST) API.
production-hardened/
Demonstrates security best practices and production hardening. Includes Trivy vulnerability scanning, non-root user configuration, input validation, and real security configurations tested with actual model serving.
Together, these examples guide us through optimization, orchestration, acceleration, modern LLM deployment, and enterprise-grade security in containerized ML workflows.
Multi-Stage Docker Builds for Smaller ML Inference Images
Naïve Dockerfiles often include training libraries, Jupyter, CUDA, FastAPI, and even datasets in a single image. The result is a container that may work, but it is heavy, slow to rebuild, and full of unnecessary software. In production MLOps, where images are pushed to registries and deployed repeatedly, these inefficiencies add up quickly.
Multi-stage builds are the solution. They let us define multiple stages in a single Dockerfile:
- One stage for building or training (with heavy dependencies).
- Another stage for runtime (lightweight, containing only what is needed for inference).
By copying only the necessary artifacts (model weights, inference code) from the build stage into the runtime stage, we keep images lean and secure.

Example: From Training to Inference
Let us say we train a PyTorch model but only need the weights and inference script in production.
# Stage 1: Training image FROM pytorch/pytorch:2.3.1-cuda12.1-cudnn8-runtime AS trainer WORKDIR /app # Install training dependencies COPY requirements-train.txt . RUN pip install --no-cache-dir -r requirements-train.txt # Copy training script and run (or in CI/CD) COPY train.py . RUN python train.py --epochs 1 --save model.pth # Stage 2: Inference image FROM python:3.11-slim WORKDIR /app # Install only inference dependencies COPY requirements-infer.txt . RUN pip install --no-cache-dir -r requirements-infer.txt # Copy trained model + inference code from stage 1 COPY --from=trainer /app/model.pth . COPY inference.py . # Default command: run the inference service CMD ["python", "inference.py"]
Why This Works Better
- Smaller Images: The runtime image does not include training dependencies (e.g., Jupyter, Matplotlib, or large compilers).
- Faster Rebuilds: Changes to
inference.pydo not invalidate the cached training stage. - More Secure: Fewer dependencies mean a smaller attack surface.
- Separation of Concerns: Training and inference environments are isolated.
Best Practices for Multi-Stage Builds in ML
- Keep training and inference requirements in separate files (
requirements-train.txt,requirements-infer.txt). - Use CUDA runtime images for inference rather than full CUDA developer images.
- In CI/CD, training often runs in one stage, and only the trained artifacts are copied to the deployable image.
- For very large models (e.g., Stable Diffusion, LLMs), save weights to object storage (Amazon Simple Storage Service (Amazon S3), Google Cloud Storage (GCS)) instead of baking them directly into the image.
With multi-stage builds, we move from a “kitchen sink” Dockerfile to a production-ready image that is lean, reproducible, and easy to deploy.
Next, we will use Docker Compose for ML Workflows to orchestrate multiple containers (FastAPI, Redis, and Postgres) in a single reproducible pipeline.
Docker Compose for ML Workflows
In real-world MLOps, a system usually needs more than just a single container. For example, we might train a model in one container, serve it in another, and add supporting services (e.g., a cache (Redis) or database (Postgres)). Managing these one by one with docker run is tedious. Docker Compose makes this easy by letting us define all services in a single YAML file.
We will build 2 setups:
- Basic Workflow: a trainer service and an API service.
- Extended Workflow: add Redis (cache) and Postgres (database).

model.pth in a shared artifacts/ directory, and the API container loads it to serve predictions to clients (source: image by the author).Step 1: Core ML Workflow (Trainer and API)
This is the minimal setup: train a model in one container, serve it from another.
Project Structure
mnist-compose/ ├─ trainer/ │ ├─ train.py │ ├─ requirements.txt │ └─ Dockerfile ├─ api/ │ ├─ inference.py │ ├─ requirements.txt │ └─ Dockerfile ├─ artifacts/ # shared folder for model.pth └─ docker-compose.yml
The artifacts/ folder is mounted as a shared volume so the trainer can save the model and the API can load it.
Trainer
trainer/train.py
This script trains a simple PyTorch Lightning model on the Modified National Institute of Standards and Technology (MNIST) dataset and saves the weights.
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
import pytorch_lightning as pl
class MNISTModel(pl.LightningModule):
def __init__(self):
super().__init__()
self.fc = nn.Sequential(
nn.Flatten(),
nn.Linear(28*28, 128), nn.ReLU(),
nn.Linear(128, 10)
)
def forward(self, x): return self.fc(x)
def training_step(self, batch, _):
x, y = batch
loss = nn.functional.cross_entropy(self(x), y)
self.log("loss", loss, prog_bar=True)
return loss
def configure_optimizers(self):
return torch.optim.Adam(self.parameters(), lr=1e-3)
# Load MNIST
transform = transforms.Compose([transforms.ToTensor()])
train_ds = datasets.MNIST("./data", train=True, download=True, transform=transform)
train_loader = DataLoader(train_ds, batch_size=64, shuffle=True)
# Train for 1 epoch
model = MNISTModel()
trainer = pl.Trainer(max_epochs=1, accelerator="cpu")
trainer.fit(model, train_loader)
# Save model
torch.save(model.state_dict(), "/app/artifacts/model.pth")
print("✅ Model saved to /app/artifacts/model.pth")
This creates a small neural net, trains for 1 epoch, and saves the weights into the shared /app/artifacts directory.
trainer/requirements.txt
torch==2.3.1 torchvision==0.18.1 pytorch-lightning==2.3.0
trainer/Dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates \
&& rm -rf /var/lib/apt/lists/*
RUN pip install --no-cache-dir -r requirements.txt
COPY train.py .
CMD ["python", "train.py"]
Explanation: This Dockerfile installs dependencies, copies train.py, and runs training.
API
api/inference.py
This FastAPI service loads the saved model and provides a /predict endpoint.
from fastapi import FastAPI, UploadFile, File
import torch
from torch import nn
from torchvision import transforms
from PIL import Image
app = FastAPI()
# Model definition
class MNISTModel(nn.Module):
def __init__(self):
super().__init__()
self.fc = nn.Sequential(
nn.Flatten(),
nn.Linear(28*28, 128), nn.ReLU(),
nn.Linear(128, 10)
)
def forward(self, x): return self.fc(x)
# Load trained weights
model = MNISTModel()
model.load_state_dict(torch.load("/app/artifacts/model.pth", map_location="cpu"))
model.eval()
transform = transforms.Compose([transforms.ToTensor()])
@app.post("/predict")
async def predict(file: UploadFile = File(...)):
image = Image.open(file.file).convert("L").resize((28, 28))
tensor = transform(image).unsqueeze(0)
with torch.no_grad():
output = model(tensor)
pred = torch.argmax(output, dim=1).item()
return {"prediction": pred}
Explanation
- Accepts an uploaded image (28×28 grayscale)
- Converts to tensor and runs inference
- Returns the predicted digit
api/requirements.txt
torch==2.3.1 torchvision==0.18.1 fastapi==0.111.0 uvicorn==0.30.0 pillow==10.4.0
api/Dockerfile
FROM python:3.11-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY inference.py . CMD ["uvicorn", "inference:app", "--host", "0.0.0.0", "--port", "8000"]
Compose File (Basic)
Docker-compose.yml
version: "3.9"
services:
trainer:
build: ./trainer
volumes:
- ./artifacts:/app/artifacts
api:
build: ./api
ports:
- "8000:8000"
volumes:
- ./artifacts:/app/artifacts
depends_on:
- trainer
Explanation
- Both services share the
artifacts/directory. - The trainer saves the model there.
- The API loads it and starts serving at port 8000.
Run with:
docker-compose up --build
Step 2: Extended Workflow (Add Redis and Postgres)
In production, we often want caching and logging:
- Redis: Store the last prediction so repeated requests can return instantly.
- Postgres: Log predictions into a database.

Extended API with Cache and DB
from fastapi import FastAPI, UploadFile, File
import torch
from torch import nn
from torchvision import transforms
from PIL import Image
import redis, psycopg2, os, io
app = FastAPI()
# Model
class MNISTModel(nn.Module):
def __init__(self):
super().__init__()
self.fc = nn.Sequential(
nn.Flatten(),
nn.Linear(28*28, 128), nn.ReLU(),
nn.Linear(128, 10)
)
def forward(self, x): return self.fc(x)
model = MNISTModel()
model.load_state_dict(torch.load("/app/artifacts/model.pth", map_location="cpu"))
model.eval()
transform = transforms.Compose([transforms.ToTensor()])
# Redis client
r = redis.Redis(host=os.getenv("REDIS_HOST", "localhost"), port=6379)
# Postgres client
conn = psycopg2.connect(
host=os.getenv("DB_HOST", "localhost"),
database=os.getenv("DB_NAME", "mlops"),
user=os.getenv("DB_USER", "user"),
password=os.getenv("DB_PASS", "pass")
)
cursor = conn.cursor()
@app.post("/predict")
async def predict(file: UploadFile = File(...)):
image_bytes = await file.read()
cache_key = f"prediction:{hash(image_bytes)}"
# 1. Try cache first
if r.get(cache_key):
return {"prediction": int(r.get(cache_key)), "source": "cache"}
# 2. Otherwise run inference
image = Image.open(io.BytesIO(image_bytes)).convert("L").resize((28, 28))
tensor = transform(image).unsqueeze(0)
with torch.no_grad():
output = model(tensor)
pred = torch.argmax(output, dim=1).item()
# 3. Store in cache + DB
r.set(cache_key, pred)
cursor.execute("INSERT INTO predictions (result) VALUES (%s);", (pred,))
conn.commit()
return {"prediction": pred, "source": "model"}
Explanation
- Cache logic: each request is hashed; if the same image is sent again, the result is returned instantly from Redis.
- DB (database) logic: every new prediction is logged to Postgres.
Extended Requirements
torch==2.3.1 torchvision==0.18.1 fastapi==0.111.0 uvicorn==0.30.0 pillow==10.4.0 redis==5.0.1 psycopg2-binary==2.9.9
Extended Compose File
version: "3.9"
services:
trainer:
build: ./trainer
volumes:
- ./artifacts:/app/artifacts
api:
build: ./api
ports:
- "8000:8000"
volumes:
- ./artifacts:/app/artifacts
depends_on:
- trainer
- redis
- db
environment:
- REDIS_HOST=redis
- DB_HOST=db
- DB_USER=user
- DB_PASS=pass
- DB_NAME=mlops
redis:
image: redis:7.2
ports:
- "6379:6379"
db:
image: postgres:15
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: pass
POSTGRES_DB: mlops
ports:
- "5432:5432"
Why This Matters
- The basic version shows how to link the trainer and API with volumes.
- The extended version shows how Compose orchestrates heterogeneous services (a cache and a DB).
- The caching logic speeds up repeated requests; the database keeps an audit log of predictions.
- This mirrors how ML APIs are deployed in production: training, serving, caching, and persistence all wired together.
Next up, we will add GPU support so training and inference containers can use NVIDIA hardware.
GPU Support in Docker and Docker Compose
Deep learning thrives on GPUs. Without GPU acceleration, training can be slow and inference for large models (e.g., LLMs and Stable Diffusion) can be impractical. Docker now provides first-class GPU support, but the way we enable it has changed over the years.
From nvidia-docker2 to NVIDIA Container Toolkit
- Legacy approach (pre-2020): We had to install
nvidia-docker2. - Modern approach: We install the NVIDIA Container Toolkit, which integrates directly with Docker and Docker Compose.
Once installed, we can expose GPUs to containers with a single flag.

Running a GPU-Enabled Container
We verify GPU access by running:
docker run --gpus all nvidia/cuda:12.3.2-runtime-ubuntu22.04 nvidia-smi
--gpus all: expose all GPUs.nvidia/cuda:12.3.2-runtime-ubuntu22.04: official NVIDIA CUDA runtime image.nvidia-smi: lists the GPUs visible inside the container.
If we see the familiar GPU table, our setup is working.

nvidia-smi. If we see a GPU table like this showing device names, CUDA version, and memory usage our NVIDIA Container Toolkit is correctly configured (source: image by the author).GPU Support in Docker Compose
Compose lets us control GPU scheduling with the deploy.resources.reservations.devices block.
Example 1: Give All GPUs to Trainer
services:
trainer:
build: ./trainer
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: all
capabilities: [gpu]
The trainer sees every GPU on the host.
Example 2: Restrict Inference API to One GPU
services:
api:
build: ./api
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: 1
capabilities: [gpu]
The inference API container will only see one GPU even if more are available.
Example 3: Pin to a Specific GPU
services:
api:
build: ./api
deploy:
resources:
reservations:
devices:
- driver: nvidia
device_ids: ["0"]
capabilities: [gpu]
This pins the service to GPU 0 only. This is useful when separating training and inference workloads.
Updating the Trainer for GPU Training
By default, our trainer used a CPU-only base image. To train on GPU:
Change the base image in trainer/Dockerfile:
FROM nvidia/cuda:12.3.2-runtime-ubuntu22.04
WORKDIR /app
COPY requirements.txt .
RUN apt-get update && apt-get install -y --no-install-recommends python3 python3-pip ca-certificates \
&& rm -rf /var/lib/apt/lists/*
RUN pip install --no-cache-dir -r requirements.txt
COPY train.py .
CMD ["python3", "train.py"]
Update the Lightning trainer in train.py:
trainer = pl.Trainer(max_epochs=1, accelerator="gpu", devices=1)
Now, when Compose schedules GPUs for the trainer, PyTorch Lightning will use them.
GPU Container Best Practices
- Use runtime images (
nvidia/cuda:xx-runtime) for serving to reduce image size and shorten pull times. - Pin CUDA and PyTorch versions for reproducibility.
- Test with
nvidia-smiinside containers to confirm GPU access. - Isolate GPUs for different services in Compose for predictable performance.
- Do not bake weights into images. Store them in shared volumes or Amazon S3.
With GPU support enabled, our ML pipelines can train faster and serve models efficiently.
Next, we will explore Docker for LLM Workloads (Ollama) and learn how to containerize large language models for reproducible, portable deployment.
How to Run Ollama in Docker for Local LLM Inference
So far, we have containerized training jobs and ML APIs. But what about large language models (LLMs) such as Llama, Mistral, or Gemma? These models are heavy, depend on GPU acceleration, and have complex serving environments. That is where Ollama comes in.

What Is Ollama?
Ollama is a lightweight runtime that lets us run open-source LLMs locally with a simple command like:
ollama run llama2
It handles model downloads, GPU usage, and inference behind the scenes.
Ollama has gained widespread adoption because:
- It works across macOS, Linux, and Docker.
- It supports many community models (e.g., Llama, Mistral, Gemma, and Code Llama).
- It integrates well with developer workflows (REST API, Compose, Kubernetes (k8s)).
Running Ollama in Docker
The Ollama team now publishes official Docker images, which makes running models in containers trivial.
Example: Start an Ollama Container
docker run -d \ --name ollama \ -p 11434:11434 \ ollama/ollama:latest
- Runs Ollama as a container
- Exposes a REST API at
http://localhost:11434 - We can now interact with it like any ML API
Test with:
curl http://localhost:11434/api/generate -d '{
"model": "llama2",
"prompt": "Hello, world!"
}'
The commands below confirm that our Ollama Docker container is alive and responding:
docker runstarts the Ollama service and exposes port 11434.docker psshows the container running with the correct startup command (/bin/ollama serve).- The
curlrequest to/api/generatereturns an error and that is expected.

"model 'llama2' not found") is expected. The container is working, but the model must be pulled before generation can begin (source: image by the author).Using Docker Compose for Ollama
We can integrate Ollama into a multi-service workflow using Compose just as we did with the trainer and API services.
Docker-compose.yml
version: "3.9"
services:
ollama:
image: ollama/ollama:latest
ports:
- "11434:11434"
volumes:
- ollama-models:/root/.ollama # cache models locally
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: all
capabilities: [gpu]
volumes:
ollama-models:
Explanation
- Models are cached in a volume so we do not re-download every run.
- GPU access is reserved using the same syntax as in the GPU Support section above.
- Other services (e.g., FastAPI) can talk to Ollama via REST calls.
Extending with Our Own API
Typically, we do not expose Ollama directly to users. Instead, we wrap it in an API layer (FastAPI, Flask) and add business logic, logging, or retrieval-augmented generation (RAG) pipelines.
Example service talking to Ollama:
from fastapi import FastAPI
import requests
app = FastAPI()
OLLAMA_URL = "http://ollama:11434/api/generate"
@app.get("/chat")
def chat(prompt: str):
response = requests.post(OLLAMA_URL, json={"model": "llama2", "prompt": prompt})
return response.json()
When run inside Compose, this service (api) would connect to the ollama service by name.
Why Ollama in Docker Matters for MLOps
- Reproducibility: Freeze LLM environments just like any ML pipeline.
- Portability: Deploy the same setup locally, on servers, or in Kubernetes.
- Flexibility: Swap models (Mistral, Llama, Gemma) without changing code.
- Integration: Combine with RAG systems, databases, or agent frameworks in Compose.
With Ollama and Docker, running LLMs is as easy as spinning up a container and pulling a model.
Docker Security Best Practices for Production ML Images
When we are experimenting locally, a slightly bloated Docker image is not a big deal. But in production MLOps pipelines that may run dozens of containers across clusters, image size, rebuild speed, and security vulnerabilities can make or break our deployment.
This section covers the best practices for building leaner, faster, safer ML images.

Minimize Image Size
- Use slim or distroless images
- Start from
python:3.11-slimorgcr.io/distroless/python3. - These strip out unnecessary system packages and reduce attack surface.
- Start from
- Multi-stage builds
- Keep training dependencies (e.g., Jupyter and PyTorch Lightning) in one stage.
- Copy only the trained model and serving code into a slim runtime stage.
- For example, train in
pytorch/pytorchand serve the model inpython:3.11-slim.
.dockerignore- Prevent copying large local datasets or
__pycache__folders into images.
- Prevent copying large local datasets or
Layer Caching and Reproducibility
- Order our
Dockerfilesmartly- Place
COPY requirements.txt .andRUN pip installbefore copying source code. - This way, Docker reuses the cached layer if requirements do not change.
- Place
- Pin dependencies
- Use exact versions (
torch==2.3.1nottorch>=2.0) to ensure deterministic builds.
- Use exact versions (
Security Scanning Tools
Container security is a must-have now.
- Trivy: open-source vulnerability scanner (
trivy image my-ml-app). - Snyk Container: commercial option with CI/CD integration.
- Docker Scout: built into Docker Desktop, scans for CVEs.
Run these in our CI/CD pipeline to catch known vulnerabilities before deploying.
Run as Non-Root
By default, Docker containers often run as root. For ML services exposed to the internet, that is risky.
In our Dockerfile:
RUN useradd -m mluser USER mluser
This ensures the process runs with restricted privileges.
Graceful Shutdowns
Training or inference jobs may take time to exit. If our container is killed abruptly, we might lose checkpoints.
- Use
ENTRYPOINT ["python", "app.py"]instead ofCMD "python app.py"(exec form handles signals better). - Add a
STOPSIGNAL SIGTERMline to ourDockerfileso containers shut down gracefully.
Best Practices Recap
- Start with small base images.
- Use multi-stage builds for separating training vs serving.
- Pin dependencies, leverage caching.
- Scan images for vulnerabilities.
- Drop root privileges.
- Handle graceful shutdowns to prevent model and data loss.
With these optimizations, our ML images are not only lighter and faster but also safer for production environments.
Next, we will tie this into CI/CD pipelines, where these practices become automated in our build and deployment workflows.
How to Push ML Images to Docker Hub and GitHub Container Registry
So far, we have been building Docker images locally. But in production, those images need to be stored in a registry so they can be pulled by Amazon ECS or by Kubernetes clusters such as those managed by Amazon Elastic Kubernetes Service (Amazon EKS).
Choosing a Registry
- Docker Hub: most common, public and private repos
- GitHub Container Registry (GHCR): integrates with our GitHub repos
- Amazon Elastic Container Registry (Amazon ECR), Google Cloud Artifact Registry, or Azure Container Registry (ACR): best if we are tied to a specific cloud
For this course, Docker Hub and GHCR are enough to demonstrate the idea.
Tagging Our Image
Always tag the images before pushing:
docker build -t my-ml-api . docker tag my-ml-api:latest mydockerhubuser/my-ml-api:v1.0.0
Use semantic versions (v1.0.0, v1.1.0).
- Optionally keep a latest tag for the most recent stable build.
Pushing to Docker Hub
docker login docker push mydockerhubuser/my-ml-api:v1.0.0
Pushing to GitHub Container Registry (GHCR)
# Authenticate (use a GitHub Personal Access Token) echo $CR_PAT | docker login ghcr.io -u USERNAME --password-stdin docker tag my-ml-api:latest ghcr.io/my-org/my-ml-api:v1.0.0 docker push ghcr.io/my-org/my-ml-api:v1.0.0
Why This Matters
- ECS, EKS, Lambda, and KServe all pull from registries.
- Without this step, the images stay stuck on our laptop.
- Registries are the “distribution system” for MLOps.
That is all we need at this stage: build locally → tag → push.
We will revisit this later in the Pipelines and CI/CD module to show how registries fit into automated build pipelines with GitHub Actions, Argo CD, and vulnerability scanning.
Next, we will wrap up Production-Ready Docker for MLOps with a mini-project that ties everything together: multi-stage builds, Compose orchestration, GPU support, security checks, and pushing to a registry.
Production Checklist: Hardening Our ML Images
By now, we have learned how to build Docker images, orchestrate them with Compose, enable GPUs, optimize layers, and push them to registries. To wrap up this module, let us apply those lessons in a hands-on hardening exercise that makes our ML API production-ready.
Step 1: Multi-Stage Build
Refactor our api/Dockerfile into 2 stages:
# Stage 1: Build dependencies FROM python:3.11-slim AS builder WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir --prefix=/install -r requirements.txt # Stage 2: Runtime FROM python:3.11-slim WORKDIR /app COPY --from=builder /install /usr/local COPY inference.py . USER 1000 CMD ["uvicorn", "inference:app", "--host", "0.0.0.0", "--port", "8000"]
Result: much smaller, faster image.
Step 2: Run as Non-Root
Notice the line:
USER 1000
This ensures the container runs as a non-root user for security.
Step 3: Scan for Vulnerabilities
Use Trivy to scan our image locally:
trivy image my-ml-api:latest
We will see Common Vulnerabilities and Exposures (CVE) reports. Fix them by upgrading base images or dependencies.
Step 4: Push to Registry
Tag and push to Docker Hub (or GHCR):
docker tag my-ml-api:latest mydockerhubuser/my-ml-api:v1.0.0 docker push mydockerhubuser/my-ml-api:v1.0.0
Now our production-ready ML API is stored in a registry.
Step 5: Test with Compose (Optional GPU)
Update docker-compose.yml with GPU scheduling:
services:
api:
image: mydockerhubuser/my-ml-api:v1.0.0
ports:
- "8000:8000"
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: 1
capabilities: [gpu]
Then run:
docker-compose up
Our API is now running in a production-like environment with GPU support if available.
Why This Matters
This checklist turns our dev-ready ML API into a production-hardened service:
- Smaller, faster builds.
- Secure (non-root + scanned).
- Portable (pushed to a registry).
- GPU-enabled when needed.
With this, we have completed Production-Ready Docker for MLOps.
Next, we will look beyond Compose to see how Docker Swarm scales containers and why most teams move on to Kubernetes.
Scaling ML Workloads Beyond Docker Compose with Swarm and Kubernetes
Docker Compose is great for development and small-scale ML workflows, but it has limits. Once we move to production, we will need ways to scale services across multiple machines and manage them like a cluster. That is where Docker Swarm and, more commonly today, Kubernetes come in.
Why Compose Is Not Enough
- Compose runs on a single host.
- Scaling is manual:
docker-compose up --scale api=3. - No built-in load balancing or self-healing (if a container dies, it stays dead).
- Limited role-based access or fine-grained resource management.
For real production MLOps systems, these gaps matter.
Docker Swarm: The Step Between Compose and Kubernetes
Swarm is Docker’s built-in clustering solution:
- Let us create a Swarm cluster (multiple Docker hosts joined together).
- We can deploy Compose files almost unchanged, with scaling built in.
- Provides simple load balancing and service discovery.
Example: scale our API service across 3 nodes:
docker service create --name api --replicas 3 my-ml-api:latest
Swarm automatically distributes containers across available nodes.
Why Most Teams Skip Straight to Kubernetes
In practice, Swarm is rarely used in production for ML. Most companies choose Kubernetes, either on-premises or through a managed service (e.g., Amazon EKS, Google Kubernetes Engine (GKE), or Azure Kubernetes Service (AKS)). Why?
- Ecosystem: Kubernetes has richer support for ML workloads (KServe, Kubeflow, Ray).
- Autoscaling: Built-in scaling policies for CPUs, GPUs, and queues.
- Observability: Integrates with Prometheus, Grafana, and tracing tools.
- GitOps: Tools (e.g., Argo CD) make deployment pipelines repeatable and secure.
Still, it is worth knowing Swarm exists. It shows the natural evolution from Compose → clustering → Kubernetes.
How This Fits Into MLOps
Think of it as 3 levels of maturity:
- Compose (local development): great for prototyping ML systems.
- Swarm (small clusters): rarely used today, but easy migration path.
- Kubernetes (cloud-native): the industry standard for scaling ML workloads.
With this, we have completed Production-Ready Docker for MLOps:
- From single-container basics → Compose orchestration → GPU → Ollama → optimization → registries → production checklist → scaling beyond Compose.
- We are now ready to enter the Kubernetes module, where we will learn how to scale ML workloads in the real world.
What's next? We recommend PyImageSearch University.
120+ total classes • 115+ hours of on-demand code walkthrough videos • Last updated: November 2026
★★★★★ 4.84 (128 Ratings) • 16,000+ Students Enrolled
I strongly believe that if you had the right teacher you could master computer vision and deep learning.
Do you think learning computer vision and deep learning has to be time-consuming, overwhelming, and complicated? Or has to involve complex mathematics and equations? Or requires a degree in computer science?
That’s not the case.
All you need to master computer vision and deep learning is for someone to explain things to you in simple, intuitive terms. And that’s exactly what I do. My mission is to change education and how complex Artificial Intelligence topics are taught.
If you're serious about learning computer vision, your next stop should be PyImageSearch University, the most comprehensive computer vision, deep learning, and OpenCV course online today. Here you’ll learn how to successfully and confidently apply computer vision to your work, research, and projects. Join me in computer vision mastery.
Inside PyImageSearch University you'll find:
- ✓ 120+ courses on essential computer vision, deep learning, and OpenCV topics
- ✓ 94+ Certificates of Completion
- ✓ 115+ hours of on-demand video
- ✓ Brand new courses released regularly, ensuring you can keep up with state-of-the-art techniques
- ✓ Pre-configured Jupyter Notebooks in Google Colab
- ✓ Run all code examples in your web browser — works on Windows, macOS, and Linux (no dev environment configuration required!)
- ✓ Access to centralized code repos for all 540+ tutorials on PyImageSearch
- ✓ Easy one-click downloads for code, datasets, pre-trained models, etc.
- ✓ Access on mobile, laptop, desktop, etc.
Summary
In this module, we moved beyond Docker basics and learned how to use containers in production-ready ML workflows. We began by exploring Docker Compose to orchestrate multi-service ML systems, starting with a simple trainer and API, and then extending the stack with Redis for caching and Postgres for logging.
We then enabled GPU support in Docker and Compose, learning how to schedule GPUs across services for both training and inference. Along the way, we also discovered Ollama in Docker, a modern approach to containerizing large language models and exposing them through a REST API for integration with other services.
The module also emphasized production practices. We learned how to optimize and secure ML images using slim base images, multi-stage builds, .dockerignore, non-root users, and graceful shutdowns. We pushed images to registries like Docker Hub and GHCR, preparing them for deployment to platforms such as ECS, EKS, or other cloud services.
To close out, we applied a Production Checklist exercise: refactoring with multi-stage builds, scanning images with Trivy, and pushing a hardened ML API to a registry. Finally, we went beyond Compose, seeing how Swarm fits as a small step toward clustering but understanding why Kubernetes has become the industry standard for scaling ML workloads.
Citation Information
Singh, V. “Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama,” PyImageSearch, S. Huot, A. Sharma, and P. Thakur, eds., 2026, https://pyimg.co/6l2mp
@incollection{Singh_2026_prod-ready-docker-mlops-docker-compose-gpus-ollama,
author = {Vikram Singh},
title = {{Production-Ready Docker for MLOps: Docker Compose, GPUs, and Ollama}},
booktitle = {PyImageSearch},
editor = {Susan Huot and Aditya Sharma and Piyush Thakur},
year = {2026},
url = {https://pyimg.co/6l2mp},
}
To download the source code to this post (and be notified when future tutorials are published here on PyImageSearch), simply enter your email address in the form below!

Download the Source Code and FREE 17-page Resource Guide
Enter your email address below to get a .zip of the code and a FREE 17-page Resource Guide on Computer Vision, OpenCV, and Deep Learning. Inside you'll find my hand-picked tutorials, books, courses, and libraries to help you master CV and DL!


Comment section
Hey, Adrian Rosebrock here, author and creator of PyImageSearch. While I love hearing from readers, a couple years ago I made the tough decision to no longer offer 1:1 help over blog post comments.
At the time I was receiving 200+ emails per day and another 100+ blog post comments. I simply did not have the time to moderate and respond to them all, and the sheer volume of requests was taking a toll on me.
Instead, my goal is to do the most good for the computer vision, deep learning, and OpenCV community at large by focusing my time on authoring high-quality blog posts, tutorials, and books/courses.
If you need help learning computer vision and deep learning, I suggest you refer to my full catalog of books and courses — they have helped tens of thousands of developers, students, and researchers just like yourself learn Computer Vision, Deep Learning, and OpenCV.
Click here to browse my full catalog.