how to delete unused docker images and containers

2019-06-22 09:31发布

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

3条回答
祖国的老花朵
2楼-- · 2019-06-22 09:45

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}")
查看更多
放荡不羁爱自由
3楼-- · 2019-06-22 09:45

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.

查看更多
叛逆
4楼-- · 2019-06-22 09:50

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

查看更多
登录 后发表回答