Skip to main content / پرش به محتوای اصلی

Docker & Docker Compose for Python Developers: Complete Production Guide

November 2026Updated: November 20262 min read۳ بازدید
Docker and Docker Compose guide for Python developers banner
Complete guide to Docker and Docker Compose for Python developers: Multi-stage builds, rootless security, environment configurations, and orchestration with PostgreSQL and Redis.

"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

  1. Zero Library Incompatibilities: Native C extensions (like psycopg or Pillow) are compiled directly inside the targeted Linux architecture.
  2. Rapid Multi-Service Orchestration: Spin up isolated PostgreSQL and Redis instances locally within seconds without altering host machines.
  3. 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:

text
__pycache__/
*.py[cod]
.venv/
.env
.git/
.vscode/
*.log

2. Production Multi-Stage Dockerfile

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

yaml
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

bash
# 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:

Enjoyed this article?

Share it with your friends and colleagues.

Share: