Cleaning Up Old Docker Images
Cleaning Up Old Docker Images
Quick primer on how to clean up old images in Docker. One of the first things you're gonna find when you search for this question is docker images prune
. This works, but only on dangling images. Dangling images are essentially orphaned images created as a process in making another image. They're usually generated when a Dockerfile creates a few layers during final image creation.
Thing is, when you're building images and tagging them with, for example, the build number, those images are not dangling and they will be omitted during the image prune
command. Example:
REPOSITORY TAG IMAGE ID CREATED SIZE
fancy.service latest 813d1928f6b8 3 days ago 156MB
fancy.service v10 813d1928f6b8 3 days ago 156MB
contoso.azurecr.io/fancy.service latest 813d1928f6b8 3 days ago 156MB
contoso.azurecr.io/fancy.service v10 813d1928f6b8 3 days ago 156MB
We have 4 images that are essentially the same. Perhaps today you built v11 and want to get rid of v10, or just get rid of anything older than today's. Here's how:
docker images | grep 'days ago\|weeks ago\|months ago\|years ago' | awk '{print $3}' | xargs docker rmi --force
There are 4 parts to this command.
docker images
pulls the list of all images in the system and pipes it togrep 'days ago\|months ago\|years ago'
which selects every row that has those words in it and then pipes it toawk '{print $3}'
which returns the item in the 3rd column from each row - in this case the IMAGE ID - and then pipes it toxargs docker rmi --force
which is the crown jewel of this entire command. Xargs takes each line from the previous output and passes it as a parameter to the commanddocker rmi --force
.
This should clean up all images older than today. You can remove days ago\|
if you want to keep recent images for example.
Keep in mind this command will not remove images which are in use. That is anything that's mounted as a container -- even a stopped container.