Docker Prune

Docker 在清理工作環境這方面,或者是說 Docker 的垃圾回收(Garbage Collection)機制是相對保守的,如果沒有明確指定,Docker 通常是不會主動去刪除不需要和沒在使用的東西。

因此,我們時常需要使用 docker rm 和 docker rmi 來清理工作環境,泰勞本身每天例行性的工作就是清除那些不需要的容器(Container),先列出所有容器,再依序將其刪除,如下列步驟:

$ docker ps -a
$ docker rm <container-id-1>
$ docker rm <container-id-2>
......

清除不需要的映像檔(Image)也是一樣,先列出所有映像檔,再依序將其刪除。如果需要清除的容器和映像檔很多,一個一個處理實在不是個好辦法。有些人可能會找到一些指令,透過 grep 或 awk 來過濾出想要的資訊,那個方法在很久以前很實用,但是現在已經是西元 2019 年了,當然有更好的選擇~那就是今天的主角 Prune!

參考資料:
Prune unused Docker objects  
What is a dangling image and what is an unused image ? 

清理容器

從Docker 版本 1.13.0 開始,如果需要將所有不需要、可刪除已停止運作的容器一次清除,指令非常簡單:

$ docker container prune

結果如下圖所示,這指令真的讓你瞬間變成清除達人!

雖然這指令很方便使用,不過還是要回到原始問題,如果你的容器在每一次執行結束時,都一定要清除掉,那你應該選擇在啟動容器時就一併使用 --rm 參數,會是更好的選擇喔!

清理映像檔

整理映檔之前,先來了解一下兩種時常需要被清理的映像檔類型。

Unused Images:
An unused image means that it has not been assigned or used in a container. For example, when running docker ps –a, it will list all of your exited and currently running containers. Any images shown being used inside any of containers are a "used image".

Dangling Images:
A dangling image just means that you've created the new build of the image, but it wasn't given a new name. So the old images you have becomes the "dangling image". Those old image are the ones that are untagged and displays "<none>" on its name when you run docker image ls.

Unused 指的是沒有任何容器正在使用的映像檔,Dangling 指的是名稱為 <none>沒有標籤的映像檔,通常發生在建立新的映像檔時,用了一樣的名稱與標籤,較舊的那一個就會變成 <none>。


這兩種類型的映像檔,在容量不夠時,泰勞會優先清除掉它們。首先是 Dangling 映像檔,以前會透過 -f(--filter) 參數來過濾出 Dangling 映像檔,然後用 rmi 將其刪除,如下指令:

$ docker image ls -q -f dangling=true
$ docker rmi $(docker image ls -q -f dangling=true)

現在用 prune 就方便許多了,也不容易忘記:

$ docker image prune

如果確定 Unused 映像檔也要一起刪除,就加上 -a 參數,另外也有 filter 參數可以使用。

$ docker image prune -a 

Prune 不僅可以清理容器和映像檔,也支援資料卷(Volume)和網路(Network),甚至是範圍更大的 docker system prune,方便之餘也要小心使用喔!

留言

這個網誌中的熱門文章

程式語言常用之符號與詞彙 - 中英文對照

Repo 實用指令

什麼是 Bootloader?