Source: Dev.to | Dec 26, 2025 (UTC)
The Setup I’ve been diving deeper into containerization, and today I decided to tackle a Django application. But I didn’t just want to run it; I wanted to optimize it.
The Challenge We all know Python images can get heavy fast. Between pip install and the OS layers, a simple app can end up being 1GB+ if you aren’t careful.
What I Did I learned about Multi-Stage Builds. Instead of one giant instruction set, I split my Dockerfile into two parts:
Build Stage: Uses a full Python image to handle requirements.txt and build wheels.
Run Stage: Uses a python:slim or alpine image. I copy over the installed packages from the Build Stage and leave the heavy compiler tools behind.
The Pseudo-Code Here is the logic I applied today:
Dockerfile
# Stage 1: Build FROM python:3.9 as builder WORKDIR /app COPY requirements.txt . RUN pip install --user -r requirements.txt # Stage 2: Run FROM python:3.9-slim WORKDIR /app COPY --from=builder /root/.local /root/.local COPY . . ENV PATH=/root/.local/bin:$PATH CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
Enter fullscreen mode
Exit fullscreen mode


Залишити відповідь