Package Python Apps in Docker with Multi-Stage Builds
Containerize Python applications using Docker multi-stage builds for small, secure, production-ready images.
Prerequisites
- -Docker installed
- -A Python project with requirements.txt or pyproject.toml
Steps
Create a Dockerfile with multi-stage build
Create a multi-stage Dockerfile. The builder stage installs dependencies, and the production stage copies only the installed packages, keeping the final image small.
Using python:3.12-slim instead of python:3.12 reduces the base image size from ~1GB to ~150MB.
Create a .dockerignore file
Exclude unnecessary files from the Docker build context. This speeds up builds and prevents sensitive files from being included in the image.
Build the Docker image
Build the Docker image from the Dockerfile in the current directory. Docker caches each layer, so subsequent builds with unchanged requirements are fast.
Run the container
Start a container from the image in detached mode, mapping port 8000 on the host to port 8000 in the container.
Check the image size
Verify the final image size. A well-optimized Python image with slim base should be under 200MB for most applications.
If you need an even smaller image, consider python:3.12-alpine, but be aware that some Python packages with C extensions may require additional build dependencies.
Full Script
FAQ
Discussion
Loading comments...