Skillversitas

Docker Performance Tuning

Optimizing Docker performance for faster and more efficient applications.

1. Image Optimization

# Use a minimal base image
FROM node:18-alpine

# Multi-stage build
FROM node:18 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:18-alpine
COPY --from=builder /app/dist ./dist

2. Layer Caching

# Order the instructions correctly
FROM node:18-alpine
WORKDIR /app

# Dependencies (rarely change)
COPY package*.json ./
RUN npm ci --only=production

# Source code (changes often)
COPY . .

3. Resource Limits

services:
  api:
    deploy:
      resources:
        limits:
          cpus: '1.0'
          memory: 512M
        reservations:
          cpus: '0.5'
          memory: 256M

4. Network Optimization

# Use the host network for performance
docker run -d --network host myapp

# Or use an optimized bridge network
docker network create --driver bridge --opt com.docker.network.bridge.name=br0 app-net

Use Case: Performance Tuning

version: '3.8'

services:
  api:
    build: ./backend
    deploy:
      resources:
        limits:
          cpus: '1.0'
          memory: 512M
    environment:
      - NODE_ENV=production
      - UV_THREADPOOL_SIZE=4
    networks:
      - app-net

  database:
    image: postgres:15
    deploy:
      resources:
        limits:
          cpus: '2.0'
          memory: 2G
    command: >
      postgres
      -c shared_buffers=512MB
      -c effective_cache_size=1536MB
      -c work_mem=16MB
    volumes:
      - db-data:/var/lib/postgresql/data
    networks:
      - app-net

networks:
  app-net:

volumes:
  db-data:

Everyday Use Case

Case: The application is slow.

# Check resource usage
docker stats

# Optimize PostgreSQL
docker exec myapp-db psql -U admin -c "SHOW shared_buffers;"

# Restart with the new configuration
docker-compose restart database

Disk I/O Optimization

# Use a volume for the database
docker run -d -v db-data:/var/lib/postgresql/data postgres:15

# Use tmpfs for temp files
docker run -d --tmpfs /app/temp:rw,size=100m myapp

Best Practices

  1. Use multi-stage builds: For smaller images
  2. Optimize layer caching: Order the instructions correctly
  3. Set resource limits: For every container
  4. Use volumes: For I/O intensive workloads
  5. Monitor performance: Use docker stats

Conclusion

Performance tuning improves Docker efficiency. For applications, optimizing images, resource limits, and the network is very important.