Pruning volumes

Docker volumes are used to allow for persistent access of data by containers. This data can be important and thus the commands discussed in this section should be applied with special care.

If you know that you want to reclaim space occupied by volumes and with it irreversibly destroy the underlying data, you can use the following command:

$ docker volume prune 

This command will remove all volumes that are not currently in use by at least one container.

This is a destructive command and cannot be undone. You should always create a backup of the data associated with the volumes before you delete them except when you're sure that the data has no further value.

To avoid system corruption or malfunctioning applications, Docker does not allow you to remove volumes that are currently in use by at least one container. This applies even to the situation where a volume is used by a stopped container. You always have to remove the containers that use a volume first.

A useful flag when pruning volumes is the -f or --filter flag which allows us to specify the set of volumes which we're considering for pruning. Look at the following command:

$ docker volume prune --filter 'label=demo' 

This will only apply the command to volumes that have a label with the  demo value. The filtering flag format is key=value. If there is more than one filter needed, then we can use multiple flags:

$ docker volume prune --filter 'label=demo' --filter 'label=test'

The filter flag can also be used when pruning other resources such as containers and images.