โ† Back to Blog

Python Docker Containerization: From Dev to Production

Python Docker Containerization Guide ยท 303 words

Tags: python, docker, devops, deployment

Why Docker for Python?

Docker eliminates "works on my machine" problems. Package your Python app with all dependencies into a portable container.

Minimal Dockerfile


# Multi-stage build for smaller images
FROM python:3.12-slim as builder

WORKDIR /app
COPY requirements.txt .
RUN pip install --user --no-cache-dir -r requirements.txt

FROM python:3.12-slim
WORKDIR /app

# Copy only what's needed
COPY --from=builder /root/.local /root/.local
COPY . .

# Set PATH for installed packages
ENV PATH=/root/.local/bin:$PATH
ENV PYTHONUNBUFFERED=1

EXPOSE 8000
CMD ["python", "-m", "uvicorn", "main:app", "--host", "0.0.0.0"]

Docker Compose for Multi-Service Apps


version: '3.8'
services:
  api:
    build: .
    ports:
      - "8000:8000"
    environment:
      - DATABASE_URL=postgresql://user:pass@db:5432/app
      - REDIS_URL=redis://redis:6379
    depends_on:
      - db
      - redis
    volumes:
      - ./data:/app/data
    
  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: user
      POSTGRES_PASSWORD: pass
      POSTGRES_DB: app
    volumes:
      - pgdata:/var/lib/postgresql/data
    
  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"

volumes:
  pgdata:

Best Practices

1. Use Multi-Stage Builds


# Build stage
FROM python:3.12 AS builder
RUN pip install --user -r requirements.txt

# Runtime stage (smaller, no build tools)
FROM python:3.12-slim
COPY --from=builder /root/.local /root/.local

2. Minimize Image Size


# Good: slim base
FROM python:3.12-slim

# Bad: full image
FROM python:3.12

3. Order Layers Correctly


# Copy requirements first (cached layer)
COPY requirements.txt .
RUN pip install -r requirements.txt

# Copy code last (changes often)
COPY . .

4. Use .dockerignore


__pycache__
*.pyc
.git
.env
*.md
tests/

Production Checklist

Related Products

Need pre-built Docker templates and deployment scripts? Check out our containerization packages.

[Browse the collection โ†’](https://petroleum-board-hawaii-lol.trycloudflare.com)

๐Ÿ›’ Ready to deploy?

Browse 120+ Python tools with crypto payments and instant delivery.

Browse Products โ†’