What are Docker image layers?
Docker image layers are sequences of immutable file system modifications that constitute Docker images. By extension, layers determine what files, binaries, libraries, and configurations a container running a given image has immediate access to.
Reducing docker layers and individual layer size is a good step if we want to reduce bloat in our images. It is sometimes, however, not trivial to gauge which layers add redundant elements.
Docker layer inspection using Docker CLI
The first obvious step in reducing Docker image bloat is to find comparatively large layers and inspect them. Docker CLI allows us to do this, but this functionality is somewhat hidden in the docker history
subcommand.
For example, to inspect the ubuntu
base image, we would first pull it and then run the docker history
command with the --no-trunc
and --format
options to get verbose output and select the command creating the layer and its size.
$ docker pull ubuntu
$ docker history --no-trunc --format '{{.CreatedBy}} ({{.Size}})' ubuntu
/bin/sh -c #(nop) CMD ["/bin/bash"] (0B)
/bin/sh -c #(nop) ADD file:68158f1ff76fd4de9f92666ad22571e6cd11df166255c2814a135773fdd6acd7 in / (101MB)
/bin/sh -c #(nop) LABEL org.opencontainers.image.version=24.04 (0B)
/bin/sh -c #(nop) LABEL org.opencontainers.image.ref.name=ubuntu (0B)
/bin/sh -c #(nop) ARG LAUNCHPAD_BUILD_ARCH (0B)
/bin/sh -c #(nop) ARG RELEASE (0B)
Docker layer inspection using dive
Another option to inspect Docker image layers is to use dive
. This tool offers a more comprehensive solution because it not only lets you inspect Docker images but also reports ways to shrink it.
Using dive
is very simple, since the dive project provides a container that can be pulled from Docker hub. Consequently, no installation is required although you might still want to consider installing the tool to reduce overhead (e.g. in a CI/CD pipeline).
Calling dive on the ubuntu
base image as follows, for example,
alias dive="docker run -ti --rm -v /var/run/docker.sock:/var/run/docker.sock wagoodman/dive"
dive ubuntu
will open an interactive image explorer as shown below.
There are a couple of things to note:
- the total aggregate image layer size is shown in the top left corner (69MB in this case);
- layer details are shown below the layer size;
- an efficiency score (100% in this case) is given in the bottom left corner; and,
- there is an image file system explorer on the right side that we may use to inspect the file system of the image.
If you are looking to reduce your Docker image size beyond the standard best practices, dive may be very useful.