Container Patterns
Effective container usage patterns for development and production.
Multi-Stage Builds
Reduce image size by separating build and runtime:
# Build stage
FROM python:3.11-slim AS builder
WORKDIR /app
COPY pyproject.toml .
RUN pip install build && python -m build
# Runtime stage
FROM python:3.11-slim
WORKDIR /app
COPY --from=builder /app/dist/*.whl .
RUN pip install *.whl && rm *.whl
CMD ["python", "-m", "myapp"]
Health Checks
Always include health checks:
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
CMD curl -f http://localhost:8000/health || exit 1
Docker Compose for Development
version: "3.9"
services:
app:
build: .
ports:
- "8000:8000"
volumes:
- ./src:/app/src # Hot reload
environment:
- DEBUG=true
depends_on:
db:
condition: service_healthy
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: devpass
healthcheck:
test: ["CMD", "pg_isready"]
interval: 5s
timeout: 5s
retries: 5
Security Best Practices
- Use non-root user
RUN useradd -m appuser
USER appuser
- Pin image versions
FROM python:3.11.7-slim # Not just :latest
- Scan for vulnerabilities
docker scan myimage:latest
trivy image myimage:latest
- Use
.dockerignore
.git
.env
__pycache__
*.pyc
Resource Limits
Always set limits in production:
deploy:
resources:
limits:
cpus: "1.0"
memory: 512M
reservations:
cpus: "0.25"
memory: 128M