Containerizing with Docker
Packaging the service with its entire environment so it runs the same way on your machine and on the server.
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/healthThe .dockerignore file
.git
data/
__pycache__/
*.ipynb
.envPractices
| Practice | Cause |
|---|---|
| A pinned version of the base image | A reproducible build |
| Layer order | Better caching |
| A non-root user | Security |
Tagging the image with the version, not latest only | Precise tracking and deployment |
| Vulnerability scanning | Dependencies 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
-
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.
-
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
Complete the lesson
You have completed all the lessons in the track! You can now request the track completion certificate.
Request the certificate