Skip to Content
DockerDocker layers

Docker layers

A Docker layer is a snapshot of a filesystem created by a single instruction in a Dockerfile. These layers stack on top of each other to form a Docker image.

Each time you write an instruction like RUN, COPY, or ADD in a Dockerfile, Docker creates a new layer.

🔄 Layers are:

  • Cached: Docker can reuse unchanged layers from previous builds to save time.
  • Immutable: Once created, a layer is never changed. If you update a layer, Docker makes a new one.
  • Stacked: Later layers can see the files from previous ones and build on top of them.

📜 What Are Instructions?

Instructions are the commands in your Dockerfile that describe how to build the image. Common ones include:

  • FROM: Sets the base image (creates the first layer)
  • RUN: Executes a shell command (e.g., installing packages)
  • COPY: Copies files from your host into the image
  • ADD: Like COPY, but with extras like unpacking archives
  • ENV: Sets environment variables
  • WORKDIR: Sets working directory
  • CMD / ENTRYPOINT: Defines how the container should run

Each of these (except CMD and ENTRYPOINT, which don’t always create layers) will usually result in a new layer.


🔍 Example and Layer Breakdown

Here’s a sample Dockerfile:

FROM python:3.11-slim # Layer 1 WORKDIR /app # Layer 2 COPY requirements.txt . # Layer 3 RUN pip install -r requirements.txt # Layer 4 COPY . . # Layer 5 CMD ["python", "main.py"] # Not a layer

👇 Layer Explanation:

InstructionFilesystem ChangeLayer?
FROMBase Python image
WORKDIR /appCreates /app dir
COPY requirements.txt .Adds file
RUN pip install...Installs packages
COPY . .Adds app code
CMD ["python",...]Just metadata

🔄 Why Does Layering Matter?

  • Caching: If requirements.txt hasn’t changed, Docker can reuse the result of the RUN pip install... step. But if it has changed, Docker rebuilds that and all steps after it.
  • Build speed: Minimizing cache invalidation helps make builds faster.
  • Layer size: You want fewer, smaller layers to reduce final image size.

💡 Pro Tip: Minimizing Layers

You can combine multiple RUN commands into one to reduce layers:

RUN apt-get update && apt-get install -y \ curl \ git \ && rm -rf /var/lib/apt/lists/*

This is just one instruction, so it makes one layer.


📦 How to Inspect Layers

You can view image layers with:

docker history my-image

This will show each layer, its size, and the Dockerfile command that created it.

You can also dive deeper using:

docker image inspect my-image

🧠 Summary

ConceptMeaning
InstructionA command in your Dockerfile like RUN, COPY, etc.
LayerA snapshot of filesystem changes from a single instruction.
ImageA stack of layers forming the final app environment.
Build cacheDocker reuses unchanged layers to speed up builds.
Last updated on