is there a way to instruct docker swarm to automatically run garbage collection and remove all dangling images and containers? I run docker stack rm STACK_NAME
and redeploy the stack but this keeps unused objects. I know I can run docker prune to do the cleaning but is there a way to instruct docker to do so automatically?
P.S I tried setting history retention limit according to this post
Thanks to @DhiaTN for the accurate answer. I am covering some missing points. To remove all untagged images , images with use:
You do as follow:
For more options.
prune
is the best you get, and will need to be automated on every node through something else, as the Swarm internals won't do it for you, yet. But with Services, and a Bash one-liner and global mode, it's a easy fix:90% of the time it's the old images that are taking up space, and since we're using Swarm we wouldn't want to do something on the host outside of a Swarm service, so let's run a simple one-liner in a service that will prune images once a day on every node:
docker service create --name prune-images --mode global --mount type=bind,source=/var/run/docker.sock,target=/var/run/docker.sock docker sh -c "while true; do docker image prune -af; sleep 86400; done"
Note I wouldn't delete containers manually, but rather use task history limit to control that. Let old tasks stick around (which lets you inspect them for exit codes/errors and show their logs). The default is 5 for each service, so if want to change that to 2 for all Swarm services in the cluster:
docker swarm update --task-history-limit=2
Then the old containers will cleanup earlier, and the old images used by them will get caught by prune. Note that the history includes the running one so a limit of 2 means a single shutdown container will hang around (including its inspect metadata and logs).