Docker for ML

Package a model, its dependencies and its runtime into a container image that runs the same on a laptop, a server or a GPU cluster.

Intermediate · about 6 hours · difficulty 2/5

Learn first: From Notebook to Production Code

"It works on my machine" is especially painful in ML, where results depend on exact library versions, CUDA drivers and system packages. Containers freeze the whole environment into an image.

Essentials

  • Images and containers: an image is the blueprint, a container is a running instance.
  • Dockerfile: start FROM a base image, COPY code, RUN installs, set a CMD.
  • Layer caching: copy and install requirements before copying source code so rebuilds are fast.
  • Volumes for datasets and model files you do not want baked into the image.
  • Port mapping to reach an API running inside the container.
  • docker compose to run the model API alongside a database or monitoring stack.

ML-specific concerns

  • Image size: use slim base images and multi-stage builds; install CPU-only wheels for CPU inference.
  • GPU access: use CUDA base images (or official PyTorch images) and the NVIDIA Container Toolkit, then docker run --gpus all.
  • Model weights: either bake them in for immutability or download them at startup from a registry; choose deliberately.
  • Security: run as a non-root user and never put secrets in the image.

Where it leads

The same image runs on cloud container services, Kubernetes and batch job platforms, which is why nearly every serving and pipeline tool expects one.

Good enough to move on when you can containerize a training script and an inference API, keep the image reasonably small, and run it with GPU access.

Key concepts

  • Images, containers and Dockerfiles
  • Layer caching
  • Volumes and port mapping
  • docker compose
  • Multi-stage builds and slim images
  • GPU containers
  • Non-root users and secrets

Mini project

Write a multi-stage Dockerfile for your model's prediction service, get the image under 1 GB for CPU inference, and add a docker compose file that also starts a Prometheus container scraping it.

Check yourself

Why should you copy requirements.txt and install dependencies before copying your source code in a Dockerfile?

Free resources