Filter volumes by dangling status
In this step, we will learn how to filter Docker volumes based on their "dangling" status. A dangling volume is a volume that is not currently attached to any container. These volumes can consume disk space unnecessarily.
To filter for dangling volumes, we use the --filter dangling=true
flag.
First, let's create a container and attach one of our volumes to it. We will use the ubuntu
image. If you don't have the ubuntu
image locally, Docker will pull it automatically.
docker run -d --name mycontainer -v myvolume:/app ubuntu sleep 3600
This command runs a container named mycontainer
in detached mode (-d
), mounts myvolume
to the /app
directory inside the container (-v myvolume:/app
), uses the ubuntu
image, and keeps the container running for an hour (sleep 3600
).
Now, let's list all volumes again:
docker volume ls
You will see both myvolume
and another_volume
. myvolume
is currently in use by mycontainer
. another_volume
is not attached to any container, so it is a dangling volume.
Now, let's filter for dangling volumes:
docker volume ls --filter dangling=true
You should see another_volume
listed in the output, as it is not attached to any running container.
To see volumes that are not dangling (i.e., attached to a container), you can use --filter dangling=false
.
docker volume ls --filter dangling=false
This should show myvolume
.
Finally, let's stop and remove the container we created.
docker stop mycontainer
docker rm mycontainer
Now, if you list dangling volumes again:
docker volume ls --filter dangling=true
Both myvolume
and another_volume
should now appear as dangling, because myvolume
is no longer attached to a container.