How to remove all docker images that are not associated to a container
In our previous post we showed how to prune docker images to free up space on your hard drive. However, this approach will not remove images that have tags (i.e. names) associated with them.
Often you want to remove all images that are not required by one of the containers (both running and stopped containers).
This is pretty easy:
docker image ls --format '{{.ID}}' | xargs docker image rm
This command will list all image IDs using docker image ls --format '{{.ID}}'
and run docker image rm
for every image ID.
Since docker image rm
will fail for images that are associated to either a running or a stopped container (hence that image won’t be deleted), this will only delete those images that are not associated to any container.
In case you get a lot of those error messages as output from the command:
Error response from daemon: conflict: unable to delete 1f9cfa8dc305 (cannot be forced) - image is being used by running container 22a27af7d595
Error response from daemon: conflict: unable to delete 9af515ad5c74 (must be forced) - image is being used by stopped container 2ebcbd936841
don’t worry, that’s fine, that just means one of your images is associated to a container and hence won’t be deleted.