What are Docker image layers?
· Category: Docker
Short answer
Docker images are composed of read-only layers, each created by an instruction in the Dockerfile. Layers are stacked using a union file system and cached to speed up rebuilds.
How it works
Each Dockerfile instruction generates a new layer. When you rebuild, Docker reuses cached layers for instructions that have not changed. Only layers after the first changed instruction are rebuilt. Layers are stored as diffs, making storage efficient.
Example
FROM ubuntu:22.04 # Layer 1
RUN apt-get update # Layer 2
COPY app.py /app/ # Layer 3
RUN chmod +x /app/app.py # Layer 4
CMD ["/app/app.py"] # Layer 5
View layer history:
docker history myimage
Why it matters
Understanding layers helps you write Dockerfiles that cache efficiently. Putting frequently changing instructions later in the Dockerfile maximizes cache reuse. Fewer layers also mean smaller image sizes if you minimize RUN commands.
Common issues
- Changing a file early in the Dockerfile invalidates all subsequent layer caches.
- Too many layers can slow down builds; consolidate
RUNcommands where possible. - Large layers increase push and pull times.