How to remove docker-volume of (removed) docker-container?

Viewed 5403

I have tests that runs lots of docker containers. each of them has a volume.

How can I know the volume name that I need to delete?

for example:

~ docker run -d registry:2 
~ docker volume inspect c80fc65a79039d70cf54b3af3ab66b378dec42d0757928ae94277b197d8d8104
[
    {
        "CreatedAt": "2020-08-14T11:33:50Z",
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/c80fc65a79039d70cf54b3af3ab66b378dec42d0757928ae94277b197d8d8104/_data",
        "Name": "c80fc65a79039d70cf54b3af3ab66b378dec42d0757928ae94277b197d8d8104",
        "Options": null,
        "Scope": "local"
    }
]

After manually stopping and removing the registry:2 container, the volume still exists.

I don't want to delete all volumes because some of them are still in use.

4 Answers

You don't need to determine the volume name by yourself. Actually, you have mutliple options here.

You can use the --rm Flag on docker run if you want to clean up

Reference: docs.docker.com: Clean Up (--rm)

If you set the --rm flag, Docker also removes the anonymous volumes associated with the container when the container is removed. This is similar to running docker rm -v my-container. Only volumes that are specified without a name are removed. For example, when running:

Use the docker system prune --volumes command to clean up all volumes not used by at least one container

Reference: docs.docker.com: docker system prune

Remove all unused containers, networks, images (both dangling and unreferenced), and optionally, volumes.

Get the associate volumes

If you really want to get the volumes of a container you can use the snippet

docker inspect -f '{{ .Name }}{{ printf "\n" }}{{ range .Mounts }}{{ printf "\n\t" }}{{ .Type }} {{ if eq .Type "bind" }}{{ .Source }}{{ end }}{{ .Name }} => {{ .Destination }}{{ end }}{{ printf "\n" }}' <continaer-id>

You can either delete unused volume manually:

docker volume rm c80fc65a79039d70cf54b3af3ab66b378dec42d0757928ae94277b197d8d8104

Or prune all unused volumes

docker volume prune

Remove all unused local volumes. Unused local volumes are those which are not referenced by any containers

To clean all the anonymous volumes I am using this:

docker volume ls | awk '{if (length($2)==64 && $2!~/-/ && $2!~/_/) print $2}' | xargs -L1 docker volume rm

if you are wondering why those random volumes exists please read more here

Related