Let’s quickly recap what Docker layers are before we look at how to query their size. No worries, we look at the tip of the iceberg.
What are Docker layers
Every Docker image consists of layers. A single layer is the result of a particular instruction someone wrote down in a Dockerfile
. Docker ads a new layer to the stack for each instruction of the Dockerfile
. All layers together build the final Docker image.
Every layer is represented and treated by a hash. Docker computes the hash of a layer based on different contextual information such as the modifications and the parent layer chain. (Get all nitty-gritty details about layer ids).
Inspect the size of an image
If you have ever worked with Docker, the chances are good that you have looked at the list of images on your system. The docker image ls
command not only lists image identifiers and names. Additionally, it shows the actual size of the entire image.
# list all local images
docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
ubuntu latest f643c72bc252 2 weeks ago 72.9MB
If you don’t have any image on your local machine, go ahead and pull an image of your choice from Docker Hub. For example, pull the official Ubuntu image by executing docker pull ubuntu:latest
. Now you should also see the size of the image when running docker image ls
.
However, knowing the size of the entire image is sometimes not enough.
Get the size of Docker image layers
Sometimes, you want to dive deeper. Or you have to investigate or troubleshoot to understand why an image has a specific size. Inspecting the layers of an image is helpful in these situations.
Just execute docker history ubuntu:latest
to get a list containing all layers and their size:
# inspect the layers of a Docker image
docker history ubuntu:latest
IMAGE CREATED CREATED BY SIZE
f643c72bc252 2 weeks ago /bin/sh -c #(nop) CMD ["/bin/bash"] 0B
<missing> 2 weeks ago /bin/sh -c mkdir -p /run/systemd && echo 'do… 7B
<missing> 2 weeks ago /bin/sh -c [ -z "$(apt-get indextargets)" ] 0B
<missing> 2 weeks ago /bin/sh -c set -xe && echo '#!/bin/sh' > /… 811B
<missing> 2 weeks ago /bin/sh -c #(nop) ADD file:4f15c4475fbafb3fe… 72.9MB
You can also append the -no-trunc
option to docker history
to prevent Docker CLI from truncating the output.
# show layers of an image without output truncation
docker history --no-trunc ubuntu:latest
Conclusion
Quickly identifying big layers of your Docker image is quite handy when working with new programming languages and frameworks to see if overall Docker image size and pull/push performance can be optimized.