容器中管理數(shù)據(jù)主要有兩種方式:
- 數(shù)據(jù)卷(Data Volumes)
- 數(shù)據(jù)卷容器(Data Volume Containers)
下面介紹如何在容器內(nèi)創(chuàng)建數(shù)據(jù)卷,并且把本地的目錄或文件掛載到容器內(nèi)的數(shù)據(jù)卷中。接下來,會介紹如何使用數(shù)據(jù)卷容器在容器和主機、容器和容器之間共享數(shù)據(jù),并實現(xiàn)數(shù)據(jù)的備份和恢復。
數(shù)據(jù)卷
數(shù)據(jù)卷是一個可供容器使用的特殊目錄,它繞過文件系統(tǒng),可以提供很多有用的特性:
- 數(shù)據(jù)卷在容器之間共享 和重用。
- 對數(shù)據(jù)卷的修改會立馬生效。
- 對數(shù)據(jù)卷的更新,不會影響鏡像。
- 卷會一直存在,直到?jīng)]有容器使用。
數(shù)據(jù)卷的使用,類似于Linux 下對目錄或文件進行 mount 操作。
在容器內(nèi)創(chuàng)建一個數(shù)據(jù)卷
在用 docker run 命令的時候,使用 -v 標記可以在容器內(nèi)創(chuàng)建一個數(shù)據(jù)卷。多次使用 -v 標記創(chuàng)建多個數(shù)據(jù)卷
下面使用 training/webapp 鏡像創(chuàng)建一個Web 容器,并創(chuàng)建一個數(shù)據(jù)卷掛載到容器的 /webapp 目錄:
root@localhost:~# sudo docker run -d -P --name web -v /webapp training/webapp python app.py
注意:-P 是允許外部訪問容器需要暴露的端口。
掛載一個主機目錄作為數(shù)據(jù)卷
root@localhost:~# sudo docker run -d -P --name web -v /src/webapp:/opt/webapp training/webapp python app.py
上面的命令加載主機 /src/webapp 目錄到容器的 /opt/webapp 目錄:
Docker 掛載數(shù)據(jù)卷的默認權(quán)限是讀寫(rw),用戶通過,ro 指定為只讀。
root@localhost:~# sudo docker run -d -P --name web -v /src/webapp:/opt/webapp:ro
掛載一個本地主機文件作為數(shù)據(jù)卷
root@localhost:~# sudo docker run --rm -it -v ~/.bash_history:/.bash_history ubuntu /bin/bash
這樣就可以記錄在容器輸入過的命令歷史了。
數(shù)據(jù)卷容器
如果用戶需要在容器之間共享一些持續(xù)更新的數(shù)據(jù),最簡單的方式是使用數(shù)據(jù)卷容器。
1.創(chuàng)建一個數(shù)據(jù)卷容器 dbdata, 并在其中創(chuàng)建一個數(shù)據(jù)卷掛載到 /dbdata:
root@localhost:~# sudo docker run -it -v /dbdata --name dbdata ubuntu
2.查看 /dbdata 目錄

3.在其他容器使用 --volumes-from 來掛載 dbdata 容器中的數(shù)據(jù)卷,
例如 創(chuàng)建 db1 和 db2 兩個容器,并從 dbdata 容器掛載數(shù)據(jù)卷:
root@localhost:~#sudo docker run -it --volumes-from dbdata --name db1 ubuntu
root@localhost:~# sudo docker run -it --volumes-from dbdata --name db2 ubuntu
此時容器db1 和 db2 都掛載同一個數(shù)據(jù)卷到相同的 /dbdata 目錄。三個容器任何一方在該目錄的寫入,其他容器都可以看到。
可以多次使用 --volumes-from 參數(shù)來從多個容器掛載多個數(shù)據(jù)卷。還可以從其他已經(jīng)掛載了容器卷的容器來掛載數(shù)據(jù)卷:
root@localhost:~# sudo docker run -d --name db3 --volumes-from db1 training/postgres
注意: 使用 --volumes-from 參數(shù)擾掛載數(shù)據(jù)卷的容器自身并不需要保持在運行狀態(tài)。
如果刪除了掛載的容器(包括 dbdata、db1、db2),數(shù)據(jù)卷并不會自動刪除。
利用數(shù)據(jù)卷容器遷移數(shù)據(jù)
利用數(shù)據(jù)卷容器對其中的數(shù)據(jù)進行備份、恢復,以實現(xiàn)數(shù)據(jù)遷移。
備份
使用下面的命令來備份 dbdata 數(shù)據(jù)卷容器內(nèi)的數(shù)據(jù)卷:
root@localhost:~# sudo docker run --volumes-from dbdata -v $(pwd):/backup --name worker ubuntu tar cvf /backup/backup.tar /dbdata
恢復
下面要恢復數(shù)據(jù)到一個容器
1.創(chuàng)建一個帶有數(shù)據(jù)卷的容器dbdata2:
root@localhost:~# sudo docker run -v /dbdata --name dbdata2 ubuntu /bin/bash
2.創(chuàng)建另一個新的容器,掛載 dbdata2 的容器,并使用 untar 解壓備份文件到所掛載的容器卷中:
root@localhost:~# sudo docker run --volumes-from dbdata2 -v $(pwd):/backup busybox tar xvf /backup/backup.tar
小結(jié)
數(shù)據(jù)是最寶貴的資源, Docker 無疑為數(shù)據(jù)管理提供了充分的支持。
在生產(chǎn)環(huán)境中,建議在使用容器卷或數(shù)據(jù)卷容器之外,定期將主機的本地數(shù)據(jù)進行備份,或者使用支持容錯的存儲系統(tǒng),包括 RAID或分布文件系統(tǒng),如 Ceph、GPFS、HDFS等。
參考文檔
《Docker 技術入門與實戰(zhàn)》第6章 數(shù)據(jù)管理