What You'll Learn
Beginner
- How Docker layer caching works and how to exploit it
- How to order instructions for maximum cache hits
- How to reduce image size and improve security
Layer Caching — The Key Concept
Docker caches each layer. If the instruction and inputs haven't changed, Docker reuses the cached layer. Order matters.
Bad: Cache busted on every code change
Bad Dockerfiledockerfile
FROM node:18-alpine
WORKDIR /app
COPY . . # Every code change busts cache
RUN npm install # Re-runs every time (slow!)Good: Dependencies cached separately
Good Dockerfiledockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./ # Only re-runs if deps change
RUN npm install # Cached!
COPY . . # Code changes don't bust npm installWhy this matters
With the good version, changing a line of code doesn't trigger npm install again. Build time drops from 60s to 2s.Reducing Image Size
1. Use Alpine or slim base images
Terminalbash
# Instead of:
FROM python:3.11 # ~900 MB
# Use:
FROM python:3.11-slim # ~150 MB
FROM python:3.11-alpine # ~50 MB2. Clean up in the same layer
Dockerfiledockerfile
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*3. Use .dockerignore
.dockerignoretext
node_modules
.git
*.log
.env
Dockerfile
tests/
docs/Security Best Practices
Never bake secrets
RUN echo 'API_KEY=abc123' > /app/.env — anyone who pulls the image can see your secret. Use environment variables at runtime.Practical Exercise
Build a Dockerfile the bad way
Time the build
Change one line of code and rebuild — slow!
Rewrite with good layer order
Build again — much faster!
Key Takeaways
- Order instructions: least-changing first (FROM, packages), most-changing last (code).
- Copy dependency files before code for better caching.
- Use Alpine or slim base images to reduce size.
- Clean up package caches in the same
RUNcommand. - Always use
.dockerignore.
Comments
Comments
Post a Comment