Docker Performance Optimization
This chapter covers Docker container performance optimization strategies, including image optimization, runtime tuning, and resource management.
Image Size Optimization
Choose the Right Base Image
| Base Image | Size | Use Case |
|---|---|---|
| scratch | 0 MB | Statically compiled languages (Go) |
| alpine | ~5 MB | Most scenarios |
| distroless | ~20 MB | High security requirements |
| slim | ~80-200 MB | Need more system tools |
| full | ~800 MB+ | Build stage |
Reduce Layers
dockerfile
# ✅ Single RUN, fewer layers
RUN apt-get update && \
apt-get install -y curl wget && \
apt-get clean && \
rm -rf /var/lib/apt/lists/*Multi-Stage Builds
dockerfile
FROM node:20 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/htmlBuild Speed Optimization
Leverage Build Cache
Place less-frequently-changing instructions first:
dockerfile
COPY package*.json ./
RUN npm ci
COPY . .Use BuildKit
bash
DOCKER_BUILDKIT=1 docker build -t myapp .BuildKit benefits: parallel stage builds, smarter caching, better security.
Cache Dependency Downloads
dockerfile
RUN --mount=type=cache,target=/root/.cache/pip \
pip install -r requirements.txtRuntime Optimization
CPU
bash
docker run --cpus 2 myapp # Max 2 CPUs
docker run --cpu-shares 512 myapp # CPU weight (relative)
docker run --cpuset-cpus "0,1" myapp # Pin to specific coresMemory
bash
docker run -m 512m myapp # Max 512MB
docker run -m 512m --memory-swap 1g myapp # Memory + swap = 1GBStorage
bash
docker run --tmpfs /tmp:rw,size=100m myapp # tmpfs for temp files
docker run -v mydata:/data myapp # Named volumes (faster than bind mounts)Network
bash
docker run --network host myapp # Host network (best performance, no isolation)Resource Monitoring
bash
docker stats
docker stats --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}"
docker system df
docker system df -vCleanup
bash
docker system prune -a # All unused resources
docker image prune -a # Unused images
docker volume prune # Unused volumes
docker builder prune # Build cacheOptimization Checklist
| Optimization | Impact | Priority |
|---|---|---|
| Use Alpine base images | Reduce image size | High |
| Multi-stage builds | Reduce image size | High |
| Leverage build cache | Speed up builds | High |
| .dockerignore | Speed up builds | Medium |
| Merge RUN instructions | Reduce layers | Medium |
| Resource limits | Prevent resource contention | High |
| Named volumes | Improve I/O performance | Medium |
| Enable BuildKit | Speed up builds | Medium |
Chapter Summary
Docker performance optimization spans both image building and container runtime. Choose appropriate base images, leverage build cache, and configure resource limits to significantly improve Docker efficiency.