默認(rèn)容器的數(shù)據(jù)的讀寫發(fā)生在容器的存儲層,當(dāng)容器被刪除時其上的數(shù)據(jù)將會丟失。所以我們應(yīng)該盡量保證容器存儲層不發(fā)生寫操作,為了實現(xiàn)數(shù)據(jù)的持久化存儲我們需要選擇一種方案來保存數(shù)據(jù),當(dāng)前有以下幾種方式:
- volumes
- bind mounts
- tmpfs mounts
下圖展示了這三種技術(shù):
volumes
volumes(數(shù)據(jù)卷)是一個可供一個或多個容器使用的位于宿主機(jī)上特殊目錄,它擁有以下特性:
- 數(shù)據(jù)卷可以在容器間共享和重用
- 對數(shù)據(jù)卷的寫入操作,不會對鏡像有任何影響
- 數(shù)據(jù)卷默認(rèn)會一直存在,即使容器被刪除
使用數(shù)據(jù)卷的目的是持久化容器中的數(shù)據(jù),以在容器間共享或者防止數(shù)據(jù)丟失(寫入容器存儲層的數(shù)據(jù)會丟失)。
使用數(shù)據(jù)卷的步驟一般分為兩步:
- 創(chuàng)建一個數(shù)據(jù)卷
- 使用-v或--mount參數(shù)將數(shù)據(jù)卷掛載容器指定目錄中,這樣所有該容器針對該指定目錄的寫操作都會保存在宿主機(jī)上的volume中。
volume管理
創(chuàng)建一個volume:
1
|
$ docker volume create my-vol |
查看volumes:
1
2
|
$ docker volume ls local my-vol |
1
2
3
4
5
6
7
8
9
10
11
|
$ docker volume inspect my-vol [ { "driver" : "local" , "labels" : {}, "mountpoint" : "/var/lib/docker/volumes/my-vol/_data" , "name" : "my-vol" , "options" : {}, "scope" : "local" } ] |
我么可以看到創(chuàng)建的volume my-vol保存在目錄/var/lib/docker/volumes/
下,以后所有針對該volume的寫數(shù)據(jù)都會保存中目錄/var/lib/docker/volumes/my-vol/_data
下。
刪除一個volume:
1
|
$ docker volume rm my-vol |
或者刪除所有未使用的volumes:
1
|
docker volume prune |
掛載數(shù)據(jù)卷到容器目錄
創(chuàng)建了一個volume之后,我們可以在運行容器時通過指定-v或--mount參數(shù)來使用該volume:
使用--mount
參數(shù):
1
2
3
4
|
$ docker run -d \ --name=nginxtest \ -- mount source =nginx-vol,destination= /usr/share/nginx/html \ nginx:latest |
source指定volume,destination指定容器內(nèi)的文件或文件夾。
或者使用-v參數(shù):
1
2
3
4
|
$ docker run -d \ --name=nginxtest \ - v nginx-vol: /usr/share/nginx/html \ nginx:latest |
掛載成功后,容器從/usr/share/nginx/html目錄下讀取或?qū)懭霐?shù)據(jù),實際上都是從宿主機(jī)的nginx-vol數(shù)據(jù)卷中讀取或?qū)懭霐?shù)據(jù)。因此volumes或bind mounts也可以看作是容器和宿主機(jī)共享文件的一種方式。
-v參數(shù)使用冒號分割source和destination,冒號前半部分是source,后半部分是destination。
如果你掛載一個還不存在的數(shù)據(jù)卷,docker會自動創(chuàng)建它。(因此創(chuàng)建數(shù)據(jù)卷那一步非必需)
如果容器中的待掛載的目錄不是一個空目錄,那么該目錄下的文件會被復(fù)制到數(shù)據(jù)卷中。(bind mounts下,宿主機(jī)上的目錄總會覆蓋容器中的待掛載目錄)
-v參數(shù)和--mount參數(shù)總的來說功能幾乎相同,唯一的區(qū)別是在運行一個service時只能夠--mount參數(shù)來掛載數(shù)據(jù)卷。
使用只讀數(shù)據(jù)卷
有些情況下,我們希望某個數(shù)據(jù)卷對某個容器來說是只讀的,可以通過添加readonly選項來實現(xiàn):
1
2
3
4
|
$ docker run -d \ --name=nginxtest \ -- mount source =nginx-vol,destination= /usr/share/nginx/html , readonly \ nginx:latest |
或者使用-v參數(shù):
1
2
3
4
|
$ docker run -d \ --name=nginxtest \ - v nginx-vol: /usr/share/nginx/html :ro \ nginx:latest |
volumes使用場景
請參考這篇文章:docker數(shù)據(jù)存儲總結(jié)
參考文章
https://docs.docker.com/storage/volumes/#share-data-among-machines
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對服務(wù)器之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
原文鏈接:https://www.jianshu.com/p/c763df5a3f8b