class DockerLayerSimulator:
def __init__(self, name):
self.name = name
self.layers = []
self.cache_store = {}
def add_layer(self, command, size_mb, context_checksum, execution_time_sec):
# Cache key depends on command + context hash
cache_key = f"{command}::{context_checksum}"
is_cache_hit = cache_key in self.cache_store
if is_cache_hit:
status = "CACHED"
build_time = 0.05
else:
status = "BUILD"
build_time = execution_time_sec
self.cache_store[cache_key] = True
layer_info = {
'command': command,
'size_mb': size_mb,
'status': status,
'time_sec': build_time
}
self.layers.append(layer_info)
return layer_info
def get_summary(self):
total_size = sum(l['size_mb'] for l in self.layers)
total_time = sum(l['time_sec'] for l in self.layers)
return total_size, total_time
# Scenario: Comparing Single-Stage vs Multi-Stage Container Architecture
print("=== Containerization: Docker Layering & Multi-Stage Builds ===\n")
# --- Architecture 1: Naive Single-Stage Image ---
single_stage = DockerLayerSimulator("Single-Stage Heavy Build")
print("--- 1. Building Naive Single-Stage Dockerfile ---")
single_stage.add_layer("FROM node:18-bullseye (Heavy Base SDK)", 950.0, "base_v1", 2.0)
single_stage.add_layer("COPY . . (Premature source copy)", 25.0, "src_v1", 0.5)
single_stage.add_layer("RUN npm install (Dependencies & Tooling)", 220.0, "deps_v1", 45.0)
single_stage.add_layer("RUN npm run build (Compiled Production Code)", 40.0, "build_v1", 12.0)
size_single, time_single = single_stage.get_summary()
print(f"Single-Stage Production Image Size : {size_single:.1f} MB")
print(f"Single-Stage Initial Build Time : {time_single:.2f} seconds\n")
# --- Architecture 2: Modern Multi-Stage Image ---
multi_stage = DockerLayerSimulator("Multi-Stage Optimized Build")
print("--- 2. Building Multi-Stage Optimized Dockerfile ---")
# Stage 1: Build & Compile
multi_stage.add_layer("[Stage 1] FROM node:18-bullseye AS builder", 0.0, "base_v1", 2.0) # Discarded
multi_stage.add_layer("[Stage 1] COPY package*.json ./", 0.1, "pkg_v1", 0.1)
multi_stage.add_layer("[Stage 1] RUN npm ci (Clean Dependency Install)", 0.0, "deps_v1", 45.0) # Discarded
multi_stage.add_layer("[Stage 1] COPY src/ ./src", 0.0, "src_v1", 0.2) # Discarded
multi_stage.add_layer("[Stage 1] RUN npm run build (Produce dist/ bundle)", 0.0, "build_v1", 12.0) # Discarded
# Stage 2: Minimal Production Runtime
multi_stage.add_layer("[Stage 2] FROM nginx:alpine (Minimal Edge Server)", 23.5, "nginx_v1", 1.5)
multi_stage.add_layer("[Stage 2] COPY --from=builder /app/dist /usr/share/nginx/html", 8.2, "dist_v1", 0.3)
size_multi, time_multi = multi_stage.get_summary()
print(f"Multi-Stage Production Image Size : {size_multi:.1f} MB (vs {size_single:.1f} MB)")
print(f"Multi-Stage Initial Build Time : {time_multi:.2f} seconds\n")
# --- Phase 3: Developer Modifies 1 Line of Source Code ---
print("--- 3. Re-building After 1-Line Code Change (Cache Test) ---")
# In optimized multi-stage: package.json didn't change! npm ci is CACHED!
cache_test = DockerLayerSimulator("Cached Rebuild")
cache_test.cache_store = multi_stage.cache_store.copy()
layers_rebuild = [
("[Stage 1] FROM node:18-bullseye AS builder", 0.0, "base_v1", 2.0),
("[Stage 1] COPY package*.json ./", 0.1, "pkg_v1", 0.1),
("[Stage 1] RUN npm ci (Clean Dependency Install)", 0.0, "deps_v1", 45.0), # CACHED!
("[Stage 1] COPY src/ ./src (Changed Source)", 0.0, "src_v2_EDITED", 0.2), # Cache Miss!
("[Stage 1] RUN npm run build (Produce dist/ bundle)", 0.0, "build_v2", 12.0),
("[Stage 2] FROM nginx:alpine", 23.5, "nginx_v1", 1.5),
("[Stage 2] COPY --from=builder /app/dist /usr/share/nginx/html", 8.2, "dist_v2", 0.3)
]
for cmd, sz, ctx, t in layers_rebuild:
layer = cache_test.add_layer(cmd, sz, ctx, t)
print(f" {layer['status']:7} | {layer['command'][:55]:55} ({layer['time_sec']:.2f}s)")
_, time_rebuild = cache_test.get_summary()
print(f"\nRebuild Duration with Docker Layer Caching: {time_rebuild:.2f} seconds (Saved ~45s of npm install!)")
print(f"Production Image Footprint Reduction : {((size_single - size_multi) / size_single) * 100:.1f}% smaller!")