Optimize Django Docker Builds: Cut Image Size from 1.2GB to 250MB with Multi-Stage Techniques
October 11, 2026
Stage 2 (runtime) runs on a fresh python:3.11-slim image and installs only essential runtime libraries, copies the /install from the builder stage, creates a non-root django user for security, transfers the project code with proper ownership, and runs Gunicorn as a non-privileged user.
Leverage Docker BuildKit to speed up builds, for example: DOCKER_BUILDKIT=1 docker build -t my-django-app:latest.
Adopt multi-stage builds to separate build and runtime environments, resulting in lean production images that contain only runtime dependencies.
Avoid oversized images by removing build-time dependencies, compilers, and non-essential OS packages from the final image to improve cost, security, and deployment speed.
Follow best practices such as using slim Python images, applying --no-install-recommends with apt-get, running as a non-root user, and preserving file ownership with --chown during COPY.
Using multi-stage builds and slim runtimes can reduce final image sizes from about 1.2 GB to under 250 MB, boosting security and CI/CD efficiency.
In Stage 1 (builder), use python:3.11-slim to install build tools and Python dependencies into a separate /install directory via pip with --prefix, enabling clean transfer to the runtime stage.
Summary based on 1 source
