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 imageADD: LikeCOPY, but with extras like unpacking archivesENV: Sets environment variablesWORKDIR: Sets working directoryCMD/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:
| Instruction | Filesystem Change | Layer? |
|---|---|---|
FROM | Base Python image | ✅ |
WORKDIR /app | Creates /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.txthasn’t changed, Docker can reuse the result of theRUN 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-imageThis 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
| Concept | Meaning |
|---|---|
| Instruction | A command in your Dockerfile like RUN, COPY, etc. |
| Layer | A snapshot of filesystem changes from a single instruction. |
| Image | A stack of layers forming the final app environment. |
| Build cache | Docker reuses unchanged layers to speed up builds. |