Docker Best Practices
Essential Docker practices for production. Multi-stage builds, security, and optimization.
Docker has become essential for modern deployment. Here are practices I follow.
Multi-Stage Builds
Keep images small:
# Build
FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o server
# Run
FROM alpine:3.19
RUN apk --no-cache add ca-certificates
COPY --from=builder /app/server /server
EXPOSE 8080
CMD ["/server"]
Use Specific Tags
# Bad
FROM node:latest
# Good
FROM node:20.10-alpine3.19
Run as Non-Root
RUN addgroup -S app && adduser -S app -G app
USER app
Health Checks
HEALTHCHECK --interval=30s --timeout=3s \
CMD wget -q --spider http://localhost:8080/health || exit 1
.dockerignore
node_modules
.git
.env
*.md
Dockerfile
Checklist
- Multi-stage builds
- Non-root user
- Specific tags
- Health checks
- No secrets in images
- Minimal base images