Best Practices
18. Best Practices
Section titled “18. Best Practices”✅ 1. Use Small Base Images
Section titled “✅ 1. Use Small Base Images”# Use Alpine or slim variantsFROM node:18-alpine # ~50MB# instead ofFROM node:18 # ~900MB
# Use distroless for productionFROM gcr.io/distroless/nodejs18-debian11✅ 2. Leverage Layer Caching
Section titled “✅ 2. Leverage Layer Caching”# Bad: copies everything first (cache busted on ANY change)COPY . .RUN npm install
# Good: copy package.json first (npm install cached unless deps change)COPY package*.json ./RUN npm installCOPY . .✅ 3. One Process Per Container
Section titled “✅ 3. One Process Per Container”# Bad: run Nginx + MongoDB + Redis in one container# Good: separate containers for each service
docker run -d --name web nginxdocker run -d --name db mongodocker run -d --name cache redis✅ 4. Use .dockerignore
Section titled “✅ 4. Use .dockerignore”node_modules.git.env*.logdistbuildcoverage.DS_Store✅ 5. Use Specific Tags
Section titled “✅ 5. Use Specific Tags”# BadFROM node:latest
# GoodFROM node:18.17.0-alpine3.18✅ 6. Set Resource Limits
Section titled “✅ 6. Set Resource Limits”# Limit CPU and memory to prevent runaway containersdocker run \ --memory="256m" \ --cpus="0.5" \ my-app✅ 7. Use Health Checks
Section titled “✅ 7. Use Health Checks”HEALTHCHECK --interval=30s --timeout=10s --retries=3 \ CMD curl -f http://localhost:3000/health || exit 1✅ 8. Keep Secrets Out of Images
Section titled “✅ 8. Keep Secrets Out of Images”# Never do this in Dockerfile:ENV DB_PASSWORD=mysecret
# Use --env-file or Docker Secrets insteaddocker run --env-file .env my-app✅ 9. Regular Cleanup
Section titled “✅ 9. Regular Cleanup”# Add to your routine:docker system prune # Remove unused resourcesdocker image prune -a # Remove all unused images✅ 10. Use Multi-Stage Builds (Bonus)
Section titled “✅ 10. Use Multi-Stage Builds (Bonus)”# Build stageFROM node:18 AS builderWORKDIR /appCOPY package*.json ./RUN npm installCOPY . .RUN npm run build
# Production stage (tiny!)FROM node:18-alpineWORKDIR /appCOPY --from=builder /app/dist ./distCOPY --from=builder /app/node_modules ./node_modulesCMD ["node", "dist/index.js"]