When running Docker for a long time, there are a lot of images in system. How can I remove all unused Docker images at once safety to free up the storage?
In additio
If you build these pruned images yourself (from some other, older base images) please be careful with the accepted solutions above based on docker image prune
, as the command is blunt and will try to remove also all dependencies required by your latest images (the command should be probably renamed to docker image*s* prune
).
The solution I came up for my docker image build pipelines (where there are daily builds and tags=dates are in the YYYYMMDD
format) is this:
# carefully narrow down the image to be deleted (to avoid removing useful static stuff like base images)
my_deleted_image=mirekphd/ml-cpu-py37-vsc-cust
# define the monitored image (tested for obsolescence), which will be usually the same as deleted one, unless deleting some very infrequently built image which requires a separate "clock"
monitored_image=mirekphd/ml-cache
# calculate the oldest acceptable tag (date)
date_week_ago=$(date -d "last week" '+%Y%m%d')
# get the IDs of obsolete tags of our deleted image
# note we use monitored_image to test for obsolescence
my_deleted_image_obsolete_tag_ids=$(docker images --filter="before=$monitored_image:$date_week_ago" | grep $my_deleted_image | awk '{print $3}')
# remove the obsolete tags of the deleted image
# (note it typically has to be forced using -f switch)
docker rmi -f $my_deleted_image_obsolete_tag_ids