How can I know if a Docker volume is safe to delete?

Viewed 1982

On my machine I have a few volumes whose names look like hashes. I don't remember creating them or using them. docker volume inspect shows that they were created far back in the past. Is there any way to check when they were last used, or what they were used by?

2 Answers

The only real way to find out which volumes are in use by what - that I know - is to enumerate all the containers on your system, then for each container, extract the list of volumes it references:

docker container inspect $(container) --format '{{range .Mounts}}{{.Name}}{{end}}'

To achieve your actual objective, Docker automatically protects volumes from removal if they are referenced by containers and the volume prune can do this cleanup for you:

docker volume prune

Those are anonymous volumes. They get created when you run an image that defines a VOLUME on the image, without defining a named or host volume on the container at that path. There's no metadata on the volume identifying the container that created it. Best you can do is inspect the filesystem of the volume to see if it's anything you wanted. You can run a temporary container with the volume mounted, e.g.:

$ docker volume ls
DRIVER    VOLUME NAME
local     0fba4f8f84bae8700b9b5255a5819fa1bb0bf3e22b0350254c66daa9be11e7bc
local     1fb7aea19e66f595f4900407eac7240479eed40dc3b91b72bb129182ae82240c
...

$ docker run -it --rm -v 0fba4f8f84bae8700b9b5255a5819fa1bb0bf3e22b0350254c66daa9be11e7bc:/vol busybox sh
/ # ls -al /vol
total 40
drwx------   10 root     root          4096 Mar 17  2020 .
drwxr-xr-x    1 root     root          4096 Dec  5 14:00 ..
drwxr-xr-x    4 root     root          4096 Mar 17  2020 io.containerd.content.v1.content
drwxr-xr-x    4 root     root          4096 Mar 17  2020 io.containerd.grpc.v1.cri
drwx--x--x    2 root     root          4096 Mar 17  2020 io.containerd.metadata.v1.bolt
drwx--x--x    3 root     root          4096 Mar 17  2020 io.containerd.runtime.v1.linux
drwx--x--x    2 root     root          4096 Jun 25  2019 io.containerd.runtime.v2.task
drwx------    3 root     root          4096 Mar 17  2020 io.containerd.snapshotter.v1.native
drwx------    3 root     root          4096 Mar 17  2020 io.containerd.snapshotter.v1.overlayfs
drwx------    2 root     root          4096 Mar 17  2020 tmpmounts
/ # exit

From that directory, I can see some containerd directories, and assume this was probably some kind of DinD or ephemeral builder instance in my own use cases.

Given you likely deleted the container long ago, the volumes are almost always safe to delete. You can run the following to delete anything with the long hash name. The deletes will fail if the volumes are currently in use, so there's no risk to running or even stopped containers.

docker volume ls -qf dangling=true | egrep '^[a-z0-9]{64}$' | \
  xargs --no-run-if-empty docker volume rm
Related