Doing a bit of Docker Cleanup

Every once in a while I clean up everything I created in Docker - containers, images, volumes, and the build cache.

To see how much you have stored run docker system df -

TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE
Images          6         2         2.156GB   498.9MB (23%)
Containers      2         0         176.7MB   176.7MB (100%)
Local Volumes   7         1         20.63MB   20.63MB (99%)
Build Cache     127       0         2.984GB   2.984GB

All in one

Below I show how to clean out resources one by one, but a quick way to get rid of a lot quickly is to use -

docker system prune

or docker system prune -a, running both will tell you what is going to happen.

Images

To clean out the images run docker image prune, this will delete images any that are not is use - those that don’t have other images dependant on them, or containers that use them. But you will likely have some that remain.

To see what is left behind, run docker image ls. For these ones run, docker image rim imageId, and that will clear some of them one by one, but now you will start getting the below error or something similar -

Error response from daemon: conflict: unable to delete 9033d236230a (cannot be forced) - image is being used by running container 0f6d7768b45f

In that case, you should stop, and delete the container. Then try deleting the images again.

Another error is -

Error response from daemon: conflict: unable to delete ea25002095c5 (cannot be forced) - image has dependent child images

For these you have to figure out what image is the dependent one and delete that, or nuke the whole lot (but you probably have to run it a few times) -

for imageId in $(docker image ls --format '{{.ID}}'); do docker image rm -f $imageId; done

Containers

To clean out containers, start with docker container prune.

You can run docker container ls --all and then delete one by one, or run the below to wipe them all out -

for containerId in $(docker container ls --all --format '{{.ID}}'); do docker container rm $containerId; done

You might get some errors like -

Error response from daemon: You cannot remove a running container b4f0221e230347317147b485daa4b08740bd06b4cd217347fa7f3c351f25a73f. Stop the container before attempting removal or force remove

You can either stop the container or add the --force flag to the above command.

Volume

To clear out the volumes, run docker volume prune.

Cache

And finally, to clear out the cache run docker builder prune.

Clean

TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE
Images          0         0         0B        0B
Containers      0         0         0B        0B
Local Volumes   0         0         0B        0B
Build Cache     0         0         0B        0B

There, nice and clean!

comments powered by Disqus

Related