修剪未使用的 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 主機上的所有容器(包括已停止的容器),請使用 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
規則、橋接網路裝置和路由表條目。要清理這些內容,您可以使用 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
命令是一個快捷方式,用於修剪映象、容器和網路。卷預設情況下不會被修剪,您必須為 docker system prune
命令指定 --volumes
標誌來修剪卷。
$ 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
參考文件。