📦 Write Efficient Dockerfiles
Bad Dockerfiles = large images, slow builds. Best practices reduce image size, speed up builds, improve security.
❌ Bad Dockerfile
FROM node:18 WORKDIR /app COPY . . RUN npm install RUN npm run build CMD ["npm", "start"] # 1.2GB image, slow builds
✅ Good Dockerfile
FROM node:18-alpine AS builder WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . RUN npm run build FROM node:18-alpine WORKDIR /app COPY --from=builder /app/dist ./dist RUN npm ci --production CMD ["node", "dist/server.js"] # 180MB image, fast builds
🎯 Best Practices Checklist
✅ Use smaller base images (alpine) ✅ Combine RUN commands (reduce layers) ✅ Order layers by frequency (put changes last) ✅ Use multi-stage builds ✅ Use .dockerignore ✅ Set WORKDIR ✅ Use COPY instead of ADD (unless needed) ✅ Clean up package managers (apt-get clean) ✅ Use specific versions (not latest) ✅ Run as non-root user ✅ Set health checks ✅ Use build arguments for config
💡 Key Takeaways
- Multi-stage builds reduce image size 70-90%
- Alpine base images are 10x smaller
- Layer caching speeds up builds
- Non-root user improves security
- Health checks ensure reliability
“Dockerfile best practices reduced image size from 1.2GB to 180MB. Build time from 5 minutes to 30 seconds. Essential for CI/CD.”
