
Pruning images
Next in line are images. If we want to free all space occupied by unused image layers we can use the following command:
$ docker image prune
After we reconfirm to Docker that we indeed want to free space occupied by unused image layers, those get removed. Now I have to specify what we mean when talking about unused image layers. As you recall from the previous chapter, an image is made up of a stack of immutable layers. Now, when we are building a custom image multiple times, each time making some changes in, say, the source code of the application for which we're building the image, then we are recreating layers and previous versions of the same layer become orphaned. Why is this the case? The reason is that layers are immutable, as discussed in detail in the previous chapter. Thus, when something in the source that is used to build a layer is changed, the very layer has to be rebuilt and the previous version will be abandoned.
On a system where we often build images, the number of orphaned image layers can increase substantially over time. All these orphaned layers are removed with the preceding prune command.
Similar to the prune command for containers, we can avoid Docker asking us for a confirmation by using the force flag:
$ docker image prune -f
There is an even more radical version of the image prune command. Sometimes we do not just want to remove orphaned image layers but all images that are not currently in use on our system. For this, we can use the -a (or --all) flag:
$ docker image prune --force --all
After execution of the preceding command, only images that are currently used by one or more containers will remain in our local image cache.