DEV Community

Satyam Mishra
Satyam Mishra

Posted on

Understanding Docker’s Layered Architecture: How Images Are Built Step by Step

Today i got to know about the Layered Architecture of Docker so Thought of Sharing it

When you run docker build, Docker doesn’t create one big image at once.
It builds your image layer by layer, where each Dockerfile instruction creates a new layer.

Understanding this helps you write faster, smaller, and cache-friendly images.

Image

Image


📦 What Is a Docker Image Layer?

A Docker image is a stack of immutable layers.

Each layer:

  • Represents a filesystem change
  • Is created by one Dockerfile instruction
  • Is cached and reusable
  • Is read-only once built

Final image =
Base image layers + your application layers


🛠 How Docker Builds an Image

Example Dockerfile:

FROM node:18-alpine
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
CMD ["npm", "start"]
Enter fullscreen mode Exit fullscreen mode

Docker processes this top to bottom:

  • FROM → pulls base image layers
  • WORKDIR → creates a new filesystem layer
  • COPY → adds files as a layer
  • RUN → executes a command and saves the result as a layer
  • CMD → adds metadata (not filesystem data)

Each step builds on the previous one.


⚡ Docker Build Cache (Why Order Matters)

Docker reuses layers if nothing has changed.

That’s why this pattern is important:

COPY package.json .
RUN npm install
COPY . .
Enter fullscreen mode Exit fullscreen mode

If only your source code changes:

  • npm install layer is reused
  • Build becomes much faster

🧬 How Layers Become One Image

Docker uses a union filesystem to stack layers.

[ Writable Container Layer ]
[ App Code Layer          ]
[ Dependencies Layer      ]
[ Base Image Layers       ]
Enter fullscreen mode Exit fullscreen mode
  • Image layers → read-only
  • Container adds a thin writable layer on top
  • Deleting the container removes only that top layer

📉 Common Mistake That Increases Image Size

❌ Multiple RUN commands:

RUN apt update
RUN apt install -y curl
Enter fullscreen mode Exit fullscreen mode

✅ Better:

RUN apt update && apt install -y curl
Enter fullscreen mode Exit fullscreen mode

Each RUN creates a layer, and deleted files still exist in older layers.


✅ Key Takeaways

  • Every Dockerfile instruction creates a layer
  • Layers are immutable and cached
  • Instruction order affects build speed
  • Optimized layers = faster builds & smaller images

Once you understand layers, Dockerfile optimization becomes intentional—not guesswork.


Top comments (0)