Skip to content

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 ImageSizeUse Case
scratch0 MBStatically compiled languages (Go)
alpine~5 MBMost scenarios
distroless~20 MBHigh security requirements
slim~80-200 MBNeed 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/html

Build 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.txt

Runtime 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 cores

Memory

bash
docker run -m 512m myapp               # Max 512MB
docker run -m 512m --memory-swap 1g myapp  # Memory + swap = 1GB

Storage

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 -v

Cleanup

bash
docker system prune -a       # All unused resources
docker image prune -a        # Unused images
docker volume prune          # Unused volumes
docker builder prune         # Build cache

Optimization Checklist

OptimizationImpactPriority
Use Alpine base imagesReduce image sizeHigh
Multi-stage buildsReduce image sizeHigh
Leverage build cacheSpeed up buildsHigh
.dockerignoreSpeed up buildsMedium
Merge RUN instructionsReduce layersMedium
Resource limitsPrevent resource contentionHigh
Named volumesImprove I/O performanceMedium
Enable BuildKitSpeed up buildsMedium

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.

Further Reading

Content is for learning and research only.