什麼是Docker Volume?

摘要Docker Volume,通常翻譯爲數據卷,用於保存持久化數據。當我們將數據庫例如MySQL運行在Docker容器中時,一般將數據通過Docker Volume保存在主機上,這樣即使刪除MySQL容器,數據依然保存在主機上,有效保證了數據的安全性。這篇博客將通過簡單的實踐幫助大家理解什麼是Docker Volume
什麼是Docker Volume?
本文所有命令都是在play-with-docker的在線Docker實例上執行,Docker版本爲17.05.0-ce

1. 指定Docker Volume

使用docker run命令,可以運行一個Docker容器

docker run -itd --volume /tmp/data1:/tmp/data2 --name test ubuntu bash
  • 基於ubuntu鏡像創建了一個Docker容器。
  • 容器的名稱爲test,由--name選項指定。
  • Docker Volume--volume選項指定,主機的/tmp/data1目錄與容器中的/tmp/data2目錄一一對應。

2. 查看Docker Volume

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

docker inspect --format='{{json .Mounts}}' test | python -m json.tool
[
    {
        "Destination": "/tmp/data2",
        "Mode": "",
        "Propagation": "",
        "RW": true,
        "Source": "/tmp/data1",
        "Type": "bind"
    }
]
  • 使用--format選項,可以選擇性查看需要的容器信息。.Mount爲容器的Docker Volume信息。
  • python -m json.tool可以將輸出的json字符串格式化顯示。
  • Source表示主機上的目錄,即/tmp/data1
  • Destination爲容器中的目錄,即/tmp/data2

3. 本機文件可以同步到容器

在本機/tmp/data1目錄中新建hello.txt文件

touch /tmp/data1/hello.txt
ls /tmp/data1/
hello.txt

hello.txt文件在容器/tmp/data2/目錄中可見

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

docker exec test ls /tmp/data2/
hello.txt

可知,在本機目錄/tmp/data1/的修改,可以同步到容器目錄/tmp/data2/中。

4. 容器文件可以同步到主機

在容器/tmp/data2目錄中新建world.txt文件

docker exec test touch /tmp/data2/world.txt
docker exec test ls /tmp/data2/
hello.txt
world.txt

world.txt文件在主機/tmp/data1/目錄中可見

ls /tmp/data1/
hello.txt  world.txt

可知,在容器目錄/tmp/data2/的修改,可以同步到主機目錄/tmp/data1/中。

5. 結論

Docker Volume本質上是容器與主機之間共享的目錄或者文件,這樣Docker Volume中的數據可以在主機和容器中實時同步。使用Virtualbox創建虛擬機時,也可以配置共享目錄,這與Docker Volume非常相似。

關於Fundebug

Fundebug專注於JavaScript、微信小程序、微信小遊戲、支付寶小程序、React Native、Node.js和Java實時BUG監控。 自從2016年雙十一正式上線,Fundebug累計處理了7億+錯誤事件,得到了Google、360、金山軟件、百姓網等衆多知名用戶的認可。歡迎免費試用!

什麼是Docker Volume?

版權聲明

轉載時請註明作者Fundebug以及本文地址:

https://blog.fundebug.com/2017/06/07/what-is-docker-volume/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章