How to Reduce Disk Space Used by Container Images? Practical Tips for Efficient Storage Configuration in containerd
The previous article discussed the principles of containerd’s image storage, where images are stored in two forms in containerd: one as the original image files (manifest, config, blob), and the other as snapshots of the decompressed layers. When running containers, only the decompressed layer snapshots are used, which leads to wasted space for the original image blobs in scenarios where image pushing is not needed. In environments with limited disk space, it is easy for images to consume excessive disk space. So how can we save space?
This article is based on containerd v1.7.15.
1 How to Reduce Image Storage Usage
For containers running via CRI, such as when containerd is used as the runtime for Kubernetes or when using the crictl
command to run containers:
In the containerd configuration file, set discard_unpacked_layers
to true, which allows the original image blob in the content store to be cleaned up by garbage collection (GC). Note that this option only applies to newly pulled images.
|
|
For images imported using the ctr image import
command, use the --discard-unpacked-layers
option.
2 Considerations and Risks
However, be aware that enabling discard_unpacked_layers
will prevent you from exporting and pushing images. Use this feature with caution.
3 Situations Where It’s Not Recommended
- Regular Image Repository Cleanup: If the image repository is regularly cleaned, and a running container’s image is deleted from the repository, the image cannot be re-pushed to the repository or run on other nodes.
- Sufficient Disk Space: If you have ample disk space.
4 Situations Where It’s Recommended
- Limited Disk Space: When disk space is tight.
- No Need to Push Images: If you don’t need to push images.
5 Underlying Mechanism
In the output of the ctr -n k8s.io content ls
command, a containerd.io/gc.ref.content.l.<index>
label will appear on the manifest. This label is used to mark which layers belong to this manifest. If a layer is not referenced by any manifest’s containerd.io/gc.ref.content.l.<index>
label, it will be cleaned up by garbage collection (GC).
Below is an example of the containerd.io/gc.ref.content.l.<index>
label in the manifest:
|
|
After enabling discard_unpacked_layers
, the label containerd.io/gc.ref.content.l.<index>
will not be added to the manifest during image pulls or imports. This means that the image blob will not be mapped to the manifest, allowing the image blob to be cleaned up by garbage collection (GC).
Relevant code:
|
|
6 Reference
Can I reduce the size of images in persistent storage (/var/lib/containerd)?
Allow to “discard unpacked layers” when using ctr