清理未使用的 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
命令是一個捷徑,可以清理映像檔、容器和網路。預設情況下不會清理磁碟區,您必須指定 --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
參考 以取得更多範例。