Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
best practices Docker Docker & Containers: From Zero to Production Docker Images Dockerfile Module 2 — Docker Images

Dockerfile Best Practices — Caching, Layer Order, and Image Size

Reviewed & accurate
AI Summary

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 install
Why 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 MB

2. 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 RUN command.
  • Always use .dockerignore.
Previously: Lesson 12 covered all instructions.
Today: You learned: Build faster, smaller, and safer Docker images.
Next: Lesson 14 covers multi-stage builds.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments