## Why Docker for AI?
Docker provides consistent, reproducible environments for AI model serving — eliminating "works on my machine" issues with complex ML dependencies.
### Basic AI Dockerfile
```dockerfile FROM python:3.11-slim
WORKDIR /app
# Install system 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 install --no-cache-dir -r requirements.txt
# Copy application code COPY . .
# Download model at build time (cached in layer) RUN python -c "from transformers import AutoModel; AutoModel.from_pretrained('bert-base-uncased')"
EXPOSE 8000 CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"] ```
### Multi-Stage Builds
Reduce image size by separating build and runtime:
```dockerfile # Build stage FROM python:3.11 AS builder COPY requirements.txt . RUN pip install --user --no-cache-dir -r requirements.txt
# Runtime stage FROM python:3.11-slim COPY --from=builder /root/.local /root/.local COPY . /app WORKDIR /app ENV PATH=/root/.local/bin:$PATH CMD ["uvicorn", "app:app", "--host", "0.0.0.0"] ```
### Image Size Optimization
- Use slim or alpine base images
- Install only production dependencies
- Remove build tools after compilation
- Use .dockerignore to exclude unnecessary files
- Cache model weights in a separate layer