DEV Community

Andrew
Andrew

Posted on

Docker Best Practices for Production Deployments

Docker Best Practices for Production 🐳

Multi-Stage Builds: Cut Image Size by 70%

FROM node:18 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

FROM node:18-alpine
COPY --from=builder /app/node_modules ./node_modules
COPY . .
USER node
EXPOSE 3000
CMD ["node", "app.js"]
Enter fullscreen mode Exit fullscreen mode

Result: 900MB β†’ 120MB image size

Security Hardening

Run as Non-Root

RUN useradd -m appuser
USER appuser
Enter fullscreen mode Exit fullscreen mode

Remove Package Manager

RUN apt-get purge -y --auto-remove apt-get
Enter fullscreen mode Exit fullscreen mode

Scan for Vulnerabilities

docker run --rm -v /var/run/docker.sock:/var/run/docker.sock aquasec/trivy image myapp:latest
Enter fullscreen mode Exit fullscreen mode

Performance Optimization

  1. Layer Caching - Order commands from least to most frequently changed
  2. Use .dockerignore - Exclude unnecessary files
  3. Minimize Layers - Combine RUN commands with &&
# Bad: 3 layers
RUN apt-get update
RUN apt-get install curl
RUN rm -rf /var/lib/apt/lists/*

# Good: 1 layer
RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*
Enter fullscreen mode Exit fullscreen mode

Container Networking

Health Checks

HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:3000/health || exit 1
Enter fullscreen mode Exit fullscreen mode

Port Exposure

EXPOSE 3000 8080
Enter fullscreen mode Exit fullscreen mode

Production Checklist

  • βœ… Non-root user
  • βœ… Security scanning passed
  • βœ… Health checks defined
  • βœ… Resource limits set
  • βœ… Logging configured
  • βœ… No secrets in image

Master these practices and your deployments will be rock solid. πŸš€

Top comments (0)