Concept and Structure of Layers
A Docker image is composed of multiple read-only layers. Each layer stores the filesystem changes introduced by a command in the Dockerfile. This is similar to commits in Git. It improves efficiency by storing only the changes.
Docker mounts the layers as a single filesystem using a union file system. A writable container layer is added on top of the last layer. This can be visualized as multiple transparent sheets stacked on top of each other.
How Layers Work
Each instruction in the Dockerfile creates a new layer. Let’s understand this with a simple example:
|
|
Each layer contains only the changes from the previous layer. For example, the nginx installation layer contains only the installed files and does not store the files from previous layers again.
Properties and Benefits of Layers
Key benefits of the layer approach:
Space Efficiency: The same layer can be shared among multiple images. For instance, multiple images based on ubuntu:20.04 share the base Ubuntu layer.
Build Cache: Docker caches layers individually. When building an image, layers that haven’t changed are reused from the cache.
Incremental Pulls: When pulling an image, only the layers that are not already present are pulled again.
Layers and Container Storage
Layer structure when a container runs:
- Read-only image layers
- Read-write container layer
- Copy-on-Write is used when files are modified in the container
If a file modification occurs:
- Copies the original file to the container layer
- Modifies the copied file
- Subsequent accesses go to the modified file
Layer Optimization Strategies
Practices for efficient layer organization:
- Place Frequently Changing Layers at the End:
|
|
- Combine Related Commands:
|
|
- Delete Unnecessary Files:
|
|
Multi-Stage Builds and Layers
Multi-stage builds minimize the layers in the final image:
|
|
The final image contains only the files needed for runtime, without build tools.
Layer Inspection and Analysis
Docker provides tools to inspect layer information:
|
|
This gives information about each layer’s:
- Size
- Creating command
- Creation time
- ID information
Docker’s layer system is a fundamental part of container technology. Understanding and leveraging the properties of layers facilitate efficient image management. This is particularly valuable for reducing build times and saving disk space.