# Multi-Stage Docker Builds ## Basic Multi-Stage Pattern ```dockerfile # Build stage FROM node:18-alpine AS builder WORKDIR /app COPY package*.json ./ RUN npm ci --only=production # Production stage FROM node:18-alpine AS production WORKDIR /app COPY --from=builder /app/node_modules ./node_modules COPY . . EXPOSE 3000 CMD ["npm", "start"] ``` ## Python with Virtual Environment ```dockerfile # Build stage FROM python:3.11-slim AS builder WORKDIR /app COPY requirements.txt . RUN python -m venv /opt/venv ENV PATH="/opt/venv/bin:$PATH" RUN pip install --no-cache-dir -r requirements.txt # Production stage FROM python:3.11-slim AS production WORKDIR /app COPY --from=builder /opt/venv /opt/venv ENV PATH="/opt/venv/bin:$PATH" COPY . . CMD ["python", "app.py"] ``` ## Benefits - Smaller final image size - Separation of build and runtime dependencies - Better caching strategies - Security (no build tools in production image) ## Best Practices - Use specific base image versions - Copy only necessary files to production stage - Run as non-root user in production stage - Use .dockerignore to exclude unnecessary files