首頁  >  文章  >  運維  >  docker容器重啟後資料會遺失嗎

docker容器重啟後資料會遺失嗎

WBOY
WBOY原創
2022-06-17 10:41:0011036瀏覽

docker容器重啟後資料會遺失的;但是可以利用volume或「data container」來實現資料持久化,在容器關閉之後可以利用「-v」或「–volumes-from」重新使用先前的數據,docker也可掛載宿主機磁碟目錄,用來永久儲存資料。

docker容器重啟後資料會遺失嗎

本教學操作環境:linux7.3系統、docker19.03版、Dell G3電腦。

docker容器重啟後資料會遺失嗎

會,大家在使用docker部署web應用程式或mysql資料庫時,會發現當容器重新啟動後,容器運行過程中產生的日誌或資料庫資料都會被清空。

如果你想資料持久化,需使用volume或data container,這樣在容器關閉後可以再透過-v或–volumes-from重新使用先前的資料。 docker掛載宿主機磁碟目錄,用來永久儲存資料。

建立容器時執行Docker Volume

使用docker run 指令,可以執行一個Docker容器,使用映像ubuntu/nginx,掛載本機目錄/tmp/source到容器目錄/tmp/destination

docker run -itd --volume /tmp/source:/tmp/destination --name test ubuntu/nginx bash

基於ubuntu/nginx映像建立了一個Docker容器。指定容器的名稱為test,由 ––name 選項指定。

Docker Volume 由 ––volume (可以簡寫為-v)選項指定,主機的 /tmp/source 目錄與容器中的 /tmp/destination 目錄一一對應。

查看Docker Volume

使用docker inspect 命令,可以查看Docker容器的詳細資訊:

docker inspect --format='{{json .Mounts}}'test | python -m json.tool[{"Destination": "/tmp/destination",
"Mode": "","Propagation": "","RW": true,"Source": "/tmp/source","Type": "bind"}]

使用––format 選項,可以選擇性查看需要的容器資訊。 .Mount 為容器的 Docker Volume 資訊。

python -m json.tool 可以將輸出的json字串格式化顯示。 Source 表示主機上的目錄,即 /tmp/source 。 Destination 為容器中的目錄,即 /tmp/destination。

本機檔案可以同步到容器

在本機/tmp/source目錄中新hello.txt檔案

touch /tmp/source/hello.txtls /tmp/source/hello.txt

hello.txt檔案在容器/tmp/destination/目錄中可見

使用docker exec 指令,可以在容器中執行指令。

docker exectest ls /tmp/destination/hello.txt

所以在宿主機對目錄 /tmp/source/ 的修改,可以同步到容器目錄 /tmp/destination/ 中。

容器檔案可以同步到宿主機器

在容器/tmp/destination目錄中新建world.txt檔案

docker exec test touch /tmp/destination/world.txtdocker exec test ls /tmp/destination/hello.txtworld.txt

world.txt檔案在宿主機/tmp/source/目錄中可見

ls /tmp/source/hello.txt world.txt

推薦學習:《docker影片教學

以上是docker容器重啟後資料會遺失嗎的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:docker是容器嗎下一篇:docker是容器嗎