Cleaning up your Docker space

After working with Docker for some time, you start accumulating development junk: unused volumes, networks, exited containers and unused images.

One command to Rule them all

docker system prune

Prune is a very useful command (also works for volume and network sub-commands), but it is only available for Docker 1.13.

Remove Dangling Volumes

docker volume rm $(docker volume ls -q -f "dangling=true")

Dangling volumes are volumes not in use by any container. To remove them, combine two commands: first, list volume IDs for dangling volumes and then remove them.

Remove Exited Containers

docker rm $(docker ps -q -f "status=exited")

The same principle works here too. First, list the containers (only IDs) you want to remove (with filter) and then remove them (consider rm -f to force remove).

Remove Dangling Images

docker rmi $(docker images -q -f "dangling=true")

dangling images are untagged images, that are the leaves of the images tree (not intermediary layers).

Autoremove Interactive Containers

docker run -it --rm alpine sh

When you run a new interactive container and want to avoid typing rm command after it exits, use --rm option. Then when you exit from the created container, it will be automatically destroyed.

Other links

More interesting hacks can be found at: https://codefresh.io/docker-tutorial/everyday-hacks-docker/

Show untagged images

docker images --filter "dangling=true"

would show something like -

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
<none>              <none>              8abc22fbb042        4 weeks ago         0 B
<none>              <none>              48e5f45168b9        4 weeks ago         2.489 MB
<none>              <none>              bf747efa0e2f        4 weeks ago         0 B
<none>              <none>              980fe10e5736        12 weeks ago        101.4 MB
<none>              <none>              dea752e4e117        12 weeks ago        101.4 MB
<none>              <none>              511136ea3c5a        8 months ago        0 B

Removing untagged images

docker rmi $(docker images -f "dangling=true" -q)