Docker has revolutionized how we develop, ship, and run applications. Following best practices ensures your containers are secure, efficient, and maintainable.
Dockerfile Optimization
Writing efficient Dockerfiles is crucial for reducing image size and build times. Here are some key optimization techniques.
# Use specific version tags, not 'latest'
FROM node:18-alpine
# Set working directory
WORKDIR /app
# Copy package files first for better caching
COPY package*.json ./
# Install dependencies
RUN npm ci --only=production && npm cache clean --force
# Copy application code
COPY . .
# Create non-root user
RUN addgroup -g 1001 -S nodejs && \\
adduser -S nextjs -u 1001
# Change ownership of the app directory
RUN chown -R nextjs:nodejs /app
USER nextjs
# Expose port
EXPOSE 3000\n\n# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \\
CMD curl -f http://localhost:3000/health || exit 1
# Start the application
CMD [\"npm\", \"start\"]