修剪未使用的 Docker 对象
Docker 采用保守的方法来清理未使用的对象(通常
称为 “垃圾回收”),例如镜像、容器、卷和
网络。除非您明确要求
Docker 执行此作。这可能会导致 Docker 使用额外的磁盘空间。对于每种类型的
对象,Docker 提供了一个prune
命令。此外,您还可以使用docker system prune
一次清理多种类型的对象。本主题显示
如何使用这些prune
命令。
修剪镜像
这docker image prune
命令允许您清理未使用的镜像。由
违约docker image prune
仅清理悬空镜像。悬空的镜像
是未标记且未被任何容器引用的容器。要删除
悬空镜像:
$ docker image prune
WARNING! This will remove all dangling images.
Are you sure you want to continue? [y/N] y
要删除现有容器未使用的所有镜像,请使用-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
默认情况下,系统会提示您继续。要绕过提示,请使用-f
或--force
旗。
您可以使用筛选表达式来限制修剪哪些镜像,其中包含--filter
旗。例如,仅考虑创建的超过 24 个的镜像
小时前:
$ docker image prune -a --filter "until=24h"
其他筛选表达式可用。请参阅docker image prune
参考了解更多示例。
修剪容器
当您停止容器时,除非您启动了容器,否则它不会自动删除
使用--rm
旗。要查看 Docker 主机上的所有容器,包括
stopped containers 中,使用docker ps -a
.您可能会惊讶于有多少个容器
存在,尤其是在开发系统上!已停止容器的可写层
仍然占用磁盘空间。要清理此问题,您可以使用docker container prune
命令。
$ docker container prune
WARNING! This will remove all stopped containers.
Are you sure you want to continue? [y/N] y
默认情况下,系统会提示您继续。要绕过提示,请使用-f
或--force
旗。
默认情况下,将删除所有已停止的容器。您可以使用
这--filter
旗。例如,以下命令仅删除
停止的容器超过 24 小时:
$ docker container prune --filter "until=24h"
其他筛选表达式可用。请参阅docker container prune
参考了解更多示例。
修剪卷
卷可以由一个或多个容器使用,并占用 Docker 上的空间 主机。卷永远不会自动删除,因为这样做可能会破坏 数据。
$ docker volume prune
WARNING! This will remove all volumes not used by at least one container.
Are you sure you want to continue? [y/N] y
默认情况下,系统会提示您继续。要绕过提示,请使用-f
或--force
旗。
默认情况下,将删除所有未使用的卷。您可以使用
这--filter
旗。例如,以下命令仅删除
未标有keep
标签:
$ docker volume prune --filter "label!=keep"
其他筛选表达式可用。请参阅docker volume prune
参考了解更多示例。
修剪网络
Docker 网络不会占用太多磁盘空间,但它们确实会创建iptables
rules、bridge network devices 和 routing table 条目。要清理这些东西
up 中,你可以使用docker network prune
清理未使用的网络
通过任何容器。
$ docker network prune
WARNING! This will remove all networks not used by at least one container.
Are you sure you want to continue? [y/N] y
默认情况下,系统会提示您继续。要绕过提示,请使用-f
或--force
旗。
默认情况下,将删除所有未使用的网络。您可以使用
这--filter
旗。例如,以下命令仅删除
超过 24 小时的网络:
$ docker network prune --filter "until=24h"
其他筛选表达式可用。请参阅docker network prune
参考了解更多示例。
修剪所有内容
这docker system prune
command 是修剪镜像、容器、
和网络。默认情况下,卷不会被修剪,您必须指定--volumes
的标志docker system prune
以修剪卷。
$ docker system prune
WARNING! This will remove:
- all stopped containers
- all networks not used by at least one container
- all dangling images
- unused build cache
Are you sure you want to continue? [y/N] y
要同时删除卷,请添加--volumes
旗:
$ docker system prune --volumes
WARNING! This will remove:
- all stopped containers
- all networks not used by at least one container
- all volumes not used by at least one container
- all dangling images
- all build cache
Are you sure you want to continue? [y/N] y
默认情况下,系统会提示您继续。要绕过提示,请使用-f
或--force
旗。
默认情况下,将删除所有未使用的容器、网络和镜像。您可以
使用--filter
旗。例如,以下命令
删除超过 24 小时的项目:
$ docker system prune --filter "until=24h"
其他筛选表达式可用。请参阅docker system prune
参考了解更多示例。