Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to delete unused docker images and containers automatically?

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

like image 696
tkyass Avatar asked Mar 09 '18 15:03

tkyass


3 Answers

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).

like image 125
Bret Fisher Avatar answered Sep 28 '22 06:09

Bret Fisher


Thanks to @DhiaTN for the accurate answer. I am covering some missing points. To remove all untagged images , images with use:

docker rmi $(docker images | grep "^<none>" | awk "{print $3}")
like image 41
SushilG Avatar answered Sep 28 '22 06:09

SushilG


You do as follow:

docker stop $(docker ps -a) # stop all containers
docker rm $(docker ps -a) -f # delete all containers
docker rmi $(docker images -a -q) # delete all images

For more options.

like image 43
Dhia Avatar answered Sep 28 '22 08:09

Dhia