Containerization & Deployment
Introduction
Why Containers for Microservices?
Benefit
Description
Dockerfile Best Practices
Multi-Stage Build
# Dockerfile for Python FastAPI service
# Stage 1: Build dependencies
FROM python:3.11-slim AS builder
WORKDIR /app
# Install build dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential \
&& rm -rf /var/lib/apt/lists/*
# Install Python dependencies
COPY requirements.txt .
RUN pip wheel --no-cache-dir --wheel-dir /wheels -r requirements.txt
# Stage 2: Runtime image
FROM python:3.11-slim AS runtime
# Create non-root user
RUN groupadd -r appgroup && useradd -r -g appgroup appuser
WORKDIR /app
# Install runtime dependencies only
RUN apt-get update && apt-get install -y --no-install-recommends \
curl \
&& rm -rf /var/lib/apt/lists/*
# Copy wheels from builder
COPY --from=builder /wheels /wheels
RUN pip install --no-cache-dir /wheels/* && rm -rf /wheels
# Copy application code
COPY --chown=appuser:appgroup ./src ./src
COPY --chown=appuser:appgroup ./alembic ./alembic
COPY --chown=appuser:appgroup alembic.ini .
# Switch to non-root user
USER appuser
# Expose port
EXPOSE 8000
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8000/health/live || exit 1
# Run application
CMD ["python", "-m", "uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "8000"]Layer Caching Optimization
Environment-Specific Builds
Docker Compose for Local Development
Complete Microservices Stack
Development Overrides
Production Configuration
Service Startup Scripts
Entrypoint Script
Health-Aware Startup
Container Security
Security Scanning
Secure Dockerfile
Useful Commands
Key Takeaways
What's Next?
Last updated