Problem Statement
What is the recommended approach for building Docker images in CI/CD?
Explanation
Multi-stage builds create optimized, secure Docker images by separating build and runtime dependencies. Build stage includes compilers and build tools, final stage only contains runtime requirements and artifacts. This reduces image size and attack surface.
Example multi-stage Dockerfile:
```dockerfile
# Build stage
FROM node:18 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Production stage
FROM node:18-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY package*.json ./
RUN npm ci --only=production
USER node
CMD ["node", "dist/index.js"]
```
CI/CD best practices: use layer caching (order Dockerfile from least to most frequently changing), tag images with commit SHA or version, scan for vulnerabilities (Trivy, Snyk), use BuildKit for faster builds (DOCKER_BUILDKIT=1), push to registry after successful build. Security: run as non-root user, use minimal base images (alpine), scan for vulnerabilities. Understanding Docker build optimization is crucial for efficient, secure CI/CD pipelines.
