Docker & Docker Compose for Python Developers: Complete Production Guide

"It works on my machine!" was once the single most frustrating bottleneck in software delivery. Docker transformed modern engineering by packaging code alongside runtime interpreters, system libraries, and OS configurations into portable, predictable units known as Containers.
In this comprehensive guide, you will learn how to write a production-ready, highly secure multi-stage Dockerfile tailored for Python applications (FastAPI, Django, Flask, or async bots), alongside configuring database orchestration with Docker Compose.
Short Answer: For optimal Python containerization, start with official python:3.12-slim base images, separate build toolchains via multi-stage builds, run containers as non-root users (USER appuser), and strictly exclude non-essential artifacts via .dockerignore.
Key Benefits for Python Developers
- Zero Library Incompatibilities: Native C extensions (like
psycopgorPillow) are compiled directly inside the targeted Linux architecture. - Rapid Multi-Service Orchestration: Spin up isolated PostgreSQL and Redis instances locally within seconds without altering host machines.
- Production Parity: Local development mirrors staging and production environments exactly.
1. Create .dockerignore
Prevent bulky caches, logs, and sensitive .env files from leaking into the Docker context:
__pycache__/
*.py[cod]
.venv/
.env
.git/
.vscode/
*.log
2. Production Multi-Stage Dockerfile
FROM python:3.12-slim AS builder
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential \
&& rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
RUN pip install --no-cache-dir --upgrade pip && \
pip install --no-cache-dir -r requirements.txt
# -----------------------------------------------------
FROM python:3.12-slim AS runner
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PATH="/opt/venv/bin:$PATH"
RUN addgroup --system --gid 1001 appgroup && \
adduser --system --uid 1001 --gid 1001 appuser
COPY --from=builder /opt/venv /opt/venv
COPY --chown=appuser:appgroup . .
USER appuser
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
3. Orchestration with docker-compose.yml
version: "3.8"
services:
postgres:
image: postgres:16-alpine
restart: unless-stopped
environment:
POSTGRES_USER: appuser
POSTGRES_PASSWORD: securepassword
POSTGRES_DB: project_db
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U appuser -d project_db"]
interval: 5s
timeout: 5s
retries: 5
networks:
- internal_net
backend:
build:
context: .
restart: unless-stopped
environment:
DATABASE_URL: postgresql+asyncpg://appuser:securepassword@postgres:5432/project_db
ports:
- "8000:8000"
depends_on:
postgres:
condition: service_healthy
networks:
- internal_net
volumes:
postgres_data:
networks:
internal_net:
driver: bridge
4. Key Management Commands
# Build and launch services in background
docker compose up -d --build
# Follow live logs
docker compose logs -f backend
# Safely stop containers
docker compose down
Frequently Asked Questions
Why prefer Debian slim over Alpine for Python?
Alpine uses musl libc instead of glibc. Many Python binary wheels are not compiled for musl, requiring expensive source builds during pip install. slim offers ideal compatibility and lightweight size.
Why is PYTHONUNBUFFERED=1 critical?
It prevents Python from buffering stdout and stderr streams, ensuring real-time log availability in container monitoring tools.
Tags for this article:
