Docker containerization best practices. Use when creating Dockerfiles or docker-compose configurations.
This skill provides Docker containerization best practices.
ALWAYS use multi-stage builds to minimize final image size.
# Stage 1: Builder
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Stage 2: Runner
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
# Create non-root user
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 appuser
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
USER appuser
EXPOSE 3000
CMD ["node", "dist/main.js"]
alpine or slim versions (e.g., node:20-alpine).:latest tag.# Good
FROM node:20.10.0-alpine
# Bad
FROM node:latest
Implement a non-root user for security.
RUN addgroup --system --gid 1001 appgroup
RUN adduser --system --uid 1001 appuser
USER appuser
Order instructions from least to most frequently changed.
# Good order (least changed first)
FROM node:20-alpine
WORKDIR /app
# Dependencies change less often
COPY package*.json ./
RUN npm ci --only=production
# Source changes more often
COPY . .
CMD ["node", "index.js"]
Create .dockerignore to exclude unnecessary files.
# .dockerignore
.git
.gitignore
node_modules
npm-debug.log
Dockerfile
docker-compose*.yml
.env
.env.*
*.md
.vscode
.idea
coverage
dist
.next
# docker-compose.yml