02. Docker Layer
02. Docker Layer
Docker Layer
Prerequisites
1. What is Docker Layer
A Docker layer is a read-only filesystem unit that represents a single step in building a Docker image.
A Docker image is essentially a stack of layers.
2. Docker Layer
- A Docker image = stack of layers
- Each Dockerfile instruction → creates a layer
- Layers are immutable and cacheable
- Containers add a writable layer on top
- Proper layer ordering improves build speed and efficiency
Docker images are read-only.
When a container runs, Docker adds a writable layer on top:
1
2
3
4
5
[ Writable Layer (Container) ]
[ Image Layer 4 ]
[ Image Layer 3 ]
[ Image Layer 2 ]
[ Image Layer 1 ]
All changes happen in the top writable layer
2-1. How Layers Are Created
Each instruction in a Dockerfile creates a new layer.
1
2
3
4
FROM ubuntu:22.04
RUN apt-get update
RUN apt-get install -y python3
COPY . /app
This results in:
1
2
3
4
Layer 1: Base image (ubuntu)
Layer 2: apt-get update
Layer 3: install python3
Layer 4: copy application files
Every step = one layer
2-2. Why Layers Matter
✔️ 1. Build Cache (Performance)
Docker caches layers.
If nothing changes:
- It reuses previous layers
- Avoids rebuilding everything
✔️ 2. Reusability
Multiple images can share layers:
1
2
Image A → ubuntu + python + app A
Image B → ubuntu + python + app B
ubuntu + python layers are shared
✔️ 3. Smaller Size
- Layers are reused instead of duplicated
- Saves disk space and network bandwidth
✔️ 4. Immutable
- Layers cannot be modified
- Any change creates a new layer
✔️ 5. Copy-on-Write
When a file is modified:
- It is copied to the writable layer
- Original layer remains unchanged
3. Layer Optimization Tips
❌ Inefficient
1
2
RUN apt-get update
RUN apt-get install -y python3
👉 Creates multiple layers
✅ Optimized
1
RUN apt-get update && apt-get install -y python3
👉 Single layer
✅ Optimized
Docker rebuilds layers from the point of change.
1
COPY . /app
If this changes → all layers after it rebuild
✅ Best Practice
1
2
3
4
5
# Stable layers first
RUN apt-get install -y python3
# Frequently changing files last
COPY . /app
This post is licensed under CC BY 4.0 by the author.