小贴士:Docker清理作弊手册

我在MBP上跑的Docker Desktop,可以方便的制作镜像、做一些实验验证。但是由于家境贫寒,MBP硬盘只有256GB,用了几年现在只剩下几十GB,镜像做多了,占据空间比较大,清理多余image变成了一个亟需解决的问题。

How To Remove Docker Containers, Images, Volumes, and Networks
里,作者给了一份作弊手册,来看看吧。

清理所有无用对象

docker system prune
会清理所有的stopped的容器、所有dangling状态的image、无用网络。

❯❯❯ docker system prune
WARNING! This will remove:
        - all stopped containers
        - all networks not used by at least one container
        - all dangling images
        - all dangling build cache
Are you sure you want to continue? [y/N] y

清理docker容器

清理所有stopped的容器

当我们stop docker容器的时候,docker容器并不会自动清理,除非在run的时候就添加了 --rm
选项。可以使用 docker container prune
清理,也可以 docker ps -a

❯❯❯ docker container prune
WARNING! This will remove all stopped containers.
Are you sure you want to continue? [y/N] y

停止并清理所有容器

❯❯❯ docker container stop $(docker container ls -aq)
❯❯❯ docker container rm $(docker container ls -aq)

清理镜像

清理dangling镜像

清理一些中间没用的镜像,例如同一个tag做多次docker build之后,前面的镜像会变成dangling状态。这些镜像清理是安全的。

❯❯❯ docker image prune

清理所有没有使用的镜像

慎用。如果前面已经清理了所有的容器, -a
参数会清理所有的镜像。

❯❯❯ docker image prune -a
WARNING! This will remove all images without at least one container associated to them.
Are you sure you want to continue? [y/N] y

清理volumes

docker volume prune
可以清理没有使用的volumes。

清理networks

docker network prune
可以清理没用使用的networks。