Prune volumes using label filter
In this final step, we will learn how to prune volumes based on labels. This is a powerful way to selectively remove volumes that match specific criteria, without affecting other volumes.
First, let's create a couple of new volumes with different labels so we have something to filter.
docker volume create --label env=dev dev_volume
docker volume create --label env=prod prod_volume
docker volume create --label type=data data_volume
We have created three new volumes: dev_volume
with label env=dev
, prod_volume
with label env=prod
, and data_volume
with label type=data
.
Let's list the volumes to see the newly created ones.
docker volume ls
You should see dev_volume
, prod_volume
, and data_volume
in the list.
Now, let's prune only the volumes that have the label env=dev
. We can use the --filter
flag with the label
key.
docker volume prune --filter label=env=dev
Docker will ask for confirmation. Type y
and press Enter.
The output will show that dev_volume
was removed.
Let's list the volumes again to confirm that only dev_volume
was removed.
docker volume ls
You should now see prod_volume
and data_volume
remaining.
We can also filter by labels that are not present. For example, let's prune volumes that do not have the label type=data
.
docker volume prune --filter label!=type=data
Docker will ask for confirmation. Type y
and press Enter.
The output will show that prod_volume
was removed.
Let's list the volumes one last time to see what's left.
docker volume ls
You should now only see data_volume
remaining.
This demonstrates how you can use label filters to selectively prune volumes based on your needs.