Pruning is process that any of us did at least when we need to clean the images that have piled up through our everyday work, but sometimes it’s not that black and white. Think volumes?
Docker volumes are mechanism that can be used to store data generated or/and used by containers. In very simplified terms it’s container’s external drive and if you want to understand more hit the official docs.
The definition of a volume might imply why it would be important to not delete it even when you are developing stuff locally.
Let’s imagine a scenario where you are using a named volume to persist your MongoDb data so you can try out your app without always having to seed, or you are in the middle of developing a new feature so the seed data is still in the making, and so on… You usually try to avoid running repetitive tasks as much as possible and seeding can be one of them.
Now wouldn’t be nice if there is a way to keep your precious volumes and delete all others in one command?
Pruning volumes using labels
If you have checked the
docker volume prune command
or just have run
--help you have seen the
--filter flag and that flag is the flag that we have been looking for.
So let’s add a label to our volumes:
volumes: portainer_data: cookie_jar: labels: - "dont_touch"
The example above specifies two volumes:
cookie_jar where the latter also has the label:
This label we can use as a filter that will tell docker engine to skip deleting any volume that has it.
docker volume prune -f --filter="label!=dont_touch"
docker volume prune -f --filter label!=dont_touch
-f flag will tell docker engine to not ask for confirmation, but to just go on and delete stuff.
And there you go pruning volumes without tears!
But this is just volumes, now I need to run:
docker image prune . . . :roll_eyes:
and can this be combined with
docker system prune so I actually do everything in one line as advertised?
Prune them all
Answer to the question is yes :tada:
docker system prune supports filtering using the same rule we used when pruning volumes,
so without further ado the command to the ultimate prune of volumes, images and everything except objects that have
dont_touch label is:
docker system prune -f --volumes --filter="label!=dont_touch"
If you check the volume filtering reference you
will see that you can chain multiple
--filter in your command, be aware that we are using
!= so if you specify something
docker volume prune -f --format label!=dont_touch --format label!=keep
only volume that have both labels will not get deleted.
Using label filtering when doing a system prune on your docker objects is a neat and quick way to clean up your docker environment. It does require a bit of extra work when adding labels, but docker does offer some patterns to achieve code re-usability in your docker-compose file and you can read more about it in the article I wrote a while ago Dry Docker Compose. So even this step becomes very small :smile_cat: