🐳 Dockerfile Examples Project
A comprehensive, production-ready collection of Docker examples with a focus on Multi-Stage Builds and modern containerization best practices.
🎯 Project Purpose & Why
The Challenge
Many developers struggle with Docker optimization, leading to:
- 🐘 Bloated images (often 2-5x larger than necessary)
- 🔒 Security vulnerabilities from unnecessary dependencies
- ⏱️ Slow build times and deployment cycles
- 💰 Increased cloud costs from large image sizes
Our Solution
This project provides real-world, production-ready examples that demonstrate:
- ✅ Multi-stage builds reducing image sizes by 70-90%
- ✅ Security-first approach with minimal attack surfaces
- ✅ Fast build times with layer caching optimization
- ✅ Best practices from beginner to expert level
Why Multi-Stage Builds?
Multi-stage builds separate the build environment from the runtime environment, resulting in:
- Smaller images: Only runtime dependencies included
- Better security: No build tools in production images
- Faster deployments: Less data to transfer
- Cleaner code: Organized build process
🎯 Project Overview
This repository serves as a learning resource and reference guide for Docker containerization, featuring:
- Progressive Learning: Examples range from simple single-service containers to complex multi-service architectures
- Multi-Stage Focus: Dedicated examples showing optimization techniques
- Real-world Applications: Practical examples including messaging systems, databases, web services, and more
- Best Practices: Each example demonstrates Docker best practices and optimization techniques
- Comprehensive Documentation: Detailed guides with architecture diagrams
🤔 Understanding Docker Multi-Stage Builds: The Why & How
📖 What Are Multi-Stage Builds?
Multi-stage builds allow you to use multiple FROM statements in a single Dockerfile. Each FROM instruction starts a new stage, and you can selectively copy artifacts from one stage to another, leaving behind everything you don't need.
🎯 Why Do We Need Them?
Problem 1: Bloated Images 🐘
Before Multi-Stage:
FROM python:3.11
COPY . .
RUN pip install -r requirements.txt
# Final image: 380MB (includes pip, setuptools, build tools, cache)
The Problem: The final image contains:
- ❌ Build tools (gcc, make, etc.)
- ❌ Package manager cache
- ❌ Temporary build files
- ❌ Development dependencies
- ✅ Your application (only 5-10MB!)
After Multi-Stage:
# Stage 1: Build
FROM python:3.11 AS builder
RUN pip install --user -r requirements.txt
# Stage 2: Runtime
FROM python:3.11-slim
COPY --from=builder /root/.local /root/.local
COPY . .
# Final image: 151MB (60% reduction!)
Problem 2: Security Vulnerabilities 🔒
Why it matters:
- Build tools = more attack surface
- More packages = more CVEs (Common Vulnerabilities and Exposures)
- Unused dependencies = unnecessary risk
Multi-stage solution:
- Build stage: Contains all tools needed for compilation
- Runtime stage: Only contains what's needed to run
- Result: Minimal attack surface
Problem 3: Slow Deployments ⏱️
The impact:
Single-stage Python app: 380MB
├─ Pull time: ~45 seconds
├─ Push time: ~60 seconds
└─ Storage cost: Higher
Multi-stage Python app: 151MB
├─ Pull time: ~18 seconds (60% faster!)
├─ Push time: ~24 seconds (60% faster!)
└─ Storage cost: 60% lower
In production with 100 container starts per day:
- Time saved: ~45 minutes/day
- Bandwidth saved: ~23GB/day
- Cost savings: Significant at scale
Problem 4: Complex Build Processes 🛠️
Before: Separate build and runtime Dockerfiles
Dockerfile.build # For building
Dockerfile.runtime # For production
build-script.sh # Orchestrates the process
After: One unified Dockerfile
# Everything in one place, easier to maintain
FROM node:20 AS builder
# ... build steps
FROM node:20-alpine
# ... runtime steps
🔧 How Do Multi-Stage Builds Work?
The Mechanics
-
Stage Naming
FROM golang:1.21 AS builder
# ^^^^^^^ Named stage
-
Copying Between Stages
COPY --from=builder /app/binary /usr/local/bin/
# ^^^^^^^ References previous stage
-
Selective Artifact Transfer
Stage 1 (builder): Stage 2 (runtime):
├─ Source code ├─ Compiled binary ✓
├─ Build tools ├─ (minimal base)
├─ Dependencies
├─ Temp files
└─ Compiled binary ✓
Real-World Example: Go Application
Single-Stage (800MB):
FROM golang:1.21
WORKDIR /app
COPY . .
RUN go build -o server
CMD ["./server"]
# Problem: Includes entire Go toolchain!
Multi-Stage (4.58MB - 99.4% smaller!):
# Stage 1: Build
FROM golang:1.21 AS builder
WORKDIR /build
COPY . .
RUN CGO_ENABLED=0 go build -o server
# Stage 2: Runtime
FROM scratch
COPY --from=builder /build/server /server
ENTRYPOINT ["/server"]
# Only contains the binary! Nothing else.
Why this works:
- Go compiles to a static binary (no runtime dependencies needed)
scratch is literally empty (0MB base)
- Final image = just the binary (4.58MB)
🎨 Different Patterns for Different Languages
Pattern 1: Python (Virtual Environments)
# Build stage: Install dependencies in user space
FROM python:3.11 AS builder
RUN pip install --user --no-cache-dir -r requirements.txt
# Runtime stage: Copy installed packages
FROM python:3.11-slim
COPY --from=builder /root/.local /root/.local
# Why? Python needs the interpreter but not pip
Pattern 2: Node.js (Production Dependencies)
# Build stage: Install all dependencies
FROM node:20 AS builder
RUN npm ci --include=dev
# Runtime stage: Only production dependencies
FROM node:20-alpine
RUN npm ci --only=production
# Why? Separates devDependencies from production
Pattern 3: Go (Static Compilation)
# Build stage: Compile
FROM golang:1.21 AS builder
RUN go build -o app
# Runtime stage: Minimal or scratch
FROM scratch
COPY --from=builder /app/app /app
# Why? Go binaries are self-contained
📊 Impact Metrics: Real Numbers
| Application |
Single-Stage |
Multi-Stage |
Savings |
Method |
| Python Flask |
380MB |
151MB |
60% |
Slim base + user installs |
| Node.js Express |
395MB |
138MB |
65% |
Alpine + prod deps only |
| Go API |
800MB |
4.58MB |
99.4% |
Scratch base |
| Average |
~525MB |
~98MB |
81% |
Multi-stage techniques |
What this means in production:
- 1000 container pulls/day: Save 427GB bandwidth
- AWS ECR storage: $0.10/GB/month → Save ~$43/month per image
- Deployment time: 3x faster pulls and starts
- Security scans: 70-90% fewer vulnerabilities
🔐 Security Benefits Explained
Layer-by-Layer Comparison
Single-Stage Image Layers:
1. Base OS (Ubuntu) → 100MB, 200 packages
2. Build tools (gcc, make) → 150MB, 50 packages
3. Python + pip → 100MB, 30 packages
4. Application dependencies → 30MB, 20 packages
5. Application code → 5MB
───────────────────────────────
Total: 385MB, ~300 packages to scan for CVEs
Multi-Stage Image Layers:
1. Slim base (Python) → 50MB, 80 packages
2. Application dependencies → 30MB, 20 packages
3. Application code → 5MB
───────────────────────────────
Total: 85MB, ~100 packages to scan
Result: 66% fewer security surfaces
🚀 Performance Optimization Explained
Build Caching Strategy
Docker caches each layer. Multi-stage builds optimize this:
# ❌ Bad: Cache invalidated on any code change
FROM python:3.11
COPY . . # Copies everything
RUN pip install -r req.txt # Reinstalls every time
# ✅ Good: Dependencies cached separately
FROM python:3.11 AS builder
COPY requirements.txt . # Only copy what's needed
RUN pip install -r req.txt # Cached unless req.txt changes
COPY . . # Code changes don't break cache
Real-world impact:
- First build: 2 minutes
- Rebuild with code changes (cache hit): 10 seconds
- 12x faster iteration during development
💡 When to Use Multi-Stage Builds
| Scenario |
Use Multi-Stage? |
Why/Why Not |
| Production deployments |
✅ Always |
Size, security, performance |
| Compiled languages (Go, Rust, Java) |
✅ Always |
Massive size savings (90%+) |
| Interpreted languages (Python, Node.js) |
✅ Recommended |
Good savings (50-70%) |
| Quick local testing |
⚠️ Optional |
Single-stage is simpler for dev |
| Simple scripts |
⚠️ Optional |
May not be worth the complexity |
🎓 Learning Progression in This Repo
- Beginner: Understand the basics →
04-python-flask-multistage/
- Intermediate: Production patterns →
01-nodejs-express-multistage/
- Advanced: Extreme optimization →
01-go-multistage/ (scratch base)
- Expert: Complex architectures → Coming soon
🏗️ Architecture Overview
graph TB
subgraph "Multi-Stage Build Process"
A[Base Image] -->|Stage 1| B[Build Stage]
B --> C[Install Build Tools]
C --> D[Compile/Build App]
D -->|Stage 2| E[Runtime Stage]
E --> F[Copy Artifacts Only]
F --> G[Final Minimal Image]
end
style A fill:#2d3748,stroke:#4299e1,stroke-width:2px,color:#fff
style B fill:#2d3748,stroke:#48bb78,stroke-width:2px,color:#fff
style C fill:#2d3748,stroke:#48bb78,stroke-width:2px,color:#fff
style D fill:#2d3748,stroke:#48bb78,stroke-width:2px,color:#fff
style E fill:#2d3748,stroke:#ed8936,stroke-width:2px,color:#fff
style F fill:#2d3748,stroke:#ed8936,stroke-width:2px,color:#fff
style G fill:#2d3748,stroke:#9f7aea,stroke-width:3px,color:#fff
Loading
📁 Project Structure