Docker Deep Dive
Go beyond basics with advanced Docker concepts for production: multi-stage builds, layer optimization, health checks, and resource management.
Multi-Stage Builds
# Build stage
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
# Production stage
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
EXPOSE 3000
CMD ["node", "dist/main.js"]
# Result: Small production image (~150MB vs ~900MB)
Docker Health Checks
# In Dockerfile
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
CMD curl -f http://localhost:3000/health || exit 1
# Check container health
docker inspect --format='{{.State.Health.Status}}' mycontainer
# healthy | unhealthy | starting
Resource Limits
# Limit CPU and memory
docker run -d \
--name web \
--cpus="1.5" \
--memory="512m" \
--memory-swap="512m" \
-p 80:80 \
nginx:alpine
# Docker Compose
services:
web:
image: nginx:alpine
deploy:
resources:
limits:
cpus: '1.5'
memory: 512M
reservations:
cpus: '0.5'
memory: 256M
Advanced Networking
# Create custom bridge network
docker network create --driver bridge \
--subnet 172.20.0.0/16 \
--ip-range 172.20.240.0/20 \
app-network
# Connect containers
docker run -d --name db --network app-network postgres:15
docker run -d --name api --network app-network myapp:latest
# Containers can now reach each other by name
# api โ db:5432 (DNS resolution)