AI Academy

Structured tracks from the basics to generative AI and agents, with sequential lessons and quizzes.

201lessons

MLOps: Deploying and Operating ML Models Intermediate 12 minutes

Containerizing with Docker

Packaging the service with its entire environment so it runs the same way on your machine and on the server.

Your progress in the track0%

A Dockerfile for a FastAPI service

FROM python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py model.joblib ./
RUN useradd --create-home appuser
USER appuser
EXPOSE 8000
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]

Building and running

docker build -t risk-model:1.0.0 .
docker run --rm -p 8000:8000 risk-model:1.0.0
curl http://localhost:8000/health

The .dockerignore file

.git
data/
__pycache__/
*.ipynb
.env

Practices

PracticeCause
A pinned version of the base imageA reproducible build
Layer orderBetter caching
A non-root userSecurity
Tagging the image with the version, not latest onlyPrecise tracking and deployment
Vulnerability scanningDependencies may contain known vulnerabilities

GPUs

Use a CUDA base image compatible with the PyTorch version, install the NVIDIA Container Toolkit on the host, then run with the option --gpus all.

On Windows, Docker Desktop runs through WSL 2; make sure it is enabled and that enough memory is allocated to containers.

Lesson terms

Container
An isolated, lightweight runtime environment that holds the application and its dependencies and shares the host operating system's kernel.
Dockerfile
A text file that specifies the steps for building a container image.

Abstract

A container bundles the application with a specific file system and dependencies, so it runs the same way wherever it is run. A Dockerfile describes the steps for building the image. Good practices: a small base image with a pinned version, installing dependencies before copying the code to benefit from layer caching, running the application as a non-root user, and not putting secrets in the image. For GPUs, CUDA base images are used with NVIDIA tools.

Review questions

  1. Why do we copy requirements.txt and install the dependencies before copying the rest of the code?

    So that the dependency layer stays cached and is not rebuilt at every code change.

  2. Where do we put passwords and API keys?

    In environment variables or a secrets manager at run time, not inside the image or in the repository.

Sources and references

  1. Docker Documentation
  2. Docker — Building best practices
  3. NVIDIA Container Toolkit

Complete the lesson