Docker Certified Associate(DCA)認證考試學習- Tmpfs Mounts Docker Certified Associate(DCA)認證相關資源、Tmpfs Mounts

Published on Tuesday, February 28, 2023

Docker Tmpfs Mounts

目前我們已經瞭解了兩種資料儲存方式 VolumeBind mount, Docker其實還有提供第三種儲特殊的存資料方法,那就是 Tmpfs mount
Tmpfs mount` 跟其它兩種寫入方式最大的不同就是它是直接寫入到 Host 的記憶體內,只要 container 一停止運行, 用此方式掛載的資料路徑會直接被清除掉
因為只會寫入到 Host 記憶體內所以很適合用臨時保存一次性生成的密鑰或一些敏感資料 mounts-tmpfs

但使用上有幾個限制

  • 不像 Volume 和 Bind mount 可以跨容器共用, Tmpfs 沒辦法同時多個容器掛載
  • 只支援 Host 環境為 Linux 作業系統的機器

接下我將建立一個 alpine container 並且掛載一個 tmpfs 路徑 /myapp

docker run -dit --tmpfs /myapp alpine

接下來進入 container 內部,看到 /myapp 已經成功掛載上去了

[node1] (local) root@192.168.0.8 ~
$ docker attach 4e6
/ # ls -l
total 8

...

drwxr-xr-x    2 root     root             6 Feb 10 16:45 mnt
drwxr-xr-x    2 root     root            40 Feb 28 13:41 myapp
drwxr-xr-x    2 root     root             6 Feb 10 16:45 opt

...

根據 tmpfs 的特性,只要 container 一停止運作,此 tmpfs 掛載路徑的資料會直接被清除掉
我們試著寫幾個檔案到 container 內部

這邊寫入一個 greet.txt 到一般的路徑,使用的是 container layer,也就是一般的可讀寫層

mkdir /hello
touch /hello/greet.txt

/ # ls /hello
greet.txt

這邊寫入一個 greetTmpfs.txt 到 Tmpfs 路徑

touch /myapp/greetTmpfs.txt

/ # ls myapp/
greetTmpfs.txt

完成後使用 exit 退出 container 內部,此時 container 會進入停止狀態
可以使用 docker start 將 container 再起啟動

[node1] (local) root@192.168.0.8 ~
$ docker ps -a
CONTAINER ID   IMAGE     COMMAND     CREATED          STATUS                     PORTS     NAMES
4e6d4fc976d1   alpine    "/bin/sh"   11 minutes ago   Exited (0) 4 seconds ago             recursing_keldysh

[node1] (local) root@192.168.0.8 ~
$ docker start 4e6d4fc976d1
4e6d4fc976d1

[node1] (local) root@192.168.0.8 ~
$ docker ps
CONTAINER ID   IMAGE     COMMAND     CREATED          STATUS          PORTS     NAMES
4e6d4fc976d1   alpine    "/bin/sh"   14 minutes ago   Up 58 seconds             recursing_keldysh

最後再次進入 container 內部,發現 greet.txt 文件還存在並沒有被刪除,不過 greetTmpfs.txt 文件已經被清除了
這是因為greet.txt保存在一般的可讀寫層,生命週期與 container 一致,資料會保存到 container 被移除為止, 此範例只是進入到停止狀態所以資料不會被刪除
greetTmpfs.txt 就不一樣了, 因為他是掛載在 tmpfs 上,也就是 Host 主機的 記憶體上, 所以只要 container 一停止運行,路徑內的資料會隨之刪除

[node1] (local) root@192.168.0.8 ~
$ docker attach 4e6d

/ # ls -l /hello/
total 4
-rw-r--r--    1 root     root             3 Feb 28 13:50 greet.txt

/ # ls -l /myapp
total 0

Summary

今天學習了資料儲存的第三種方法,基本上是這三種方法裡面讀寫速度最快的,但是也是最不穩定的,可能應為你的程式丟出 exception 時, 意外造成 container 重起,這段時間的資料就全部被清除掉了,大家可以看自己的需求來使用