Tags: python, docker, devops, deployment
Docker eliminates "works on my machine" problems. Package your Python app with all dependencies into a portable container.
# 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"]
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:
# 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
# Good: slim base
FROM python:3.12-slim
# Bad: full image
FROM python:3.12
# Copy requirements first (cached layer)
COPY requirements.txt .
RUN pip install -r requirements.txt
# Copy code last (changes often)
COPY . .
__pycache__
*.pyc
.git
.env
*.md
tests/
Need pre-built Docker templates and deployment scripts? Check out our containerization packages.
[Browse the collection โ](https://petroleum-board-hawaii-lol.trycloudflare.com)
Browse 120+ Python tools with crypto payments and instant delivery.
Browse Products โ