19-Docker數據持久化

什麼是Docker數據持久化

容器在運行時會在鏡像層上加上一層:可寫層。
當刪除容器時,可寫層就會一起被刪除,數據丟失。
數據持久化就是就是將數據持久化保存,刪除容器之後,數據仍然存在。

方法1-掛載本地目錄到容器中

  • 掛載方法
docker run -d -p 8080:80 -v /html:/usr/share/nginx/html nginx      #-v參數將本地的/html掛載到容器中的/usr/share/nginx/html
  • 實驗-nginx容器的數據持久化
mkdir /html
vim /html/index.html
    <h1>Hello eagle<h1>
docker run -d -p 8080:80 -v /html:/usr/share/nginx/html nginx
firewall-cmd --add-port=8080/tcp
firewall-cmd --add-port=8080/tcp --per
#測試:http://192.168.191.131:8080/
  • 掛載爲只讀模式
-v /a:/b:ro	#掛載爲只讀模式(read only)

方法2-數據卷

數據卷和本機被掛載目錄相似,同樣使用-v掛載容器中。
數據卷集中保存在/var/lib/docker/volumes中。

創建數據卷
docker volume create -d local test      #創建一個名爲test的數據卷

創建之後,/var/lib/docker/volumes就會出現test的目錄。
test目錄中有一個目錄:_data。這個目錄由於保存所有數據。

查看數據卷
docker volume ls				#列出所有數據卷
docker volume inspect test		#查看詳細信息
刪除數據卷
docker volume prune				#刪除無用數據卷
docker volume rm test			#刪除數據卷test
使用數據卷
docker run -d -it -p 8800:80 -v test:/usr/share/nginx/html nginx

解釋:

和掛載一樣,使用-v命令指定數據卷
刪除容器之後,數據卷不會丟失內容
若數據卷中有數據,將數據卷中的_data目錄 掛載到 容器目錄。
若數據卷中無數據,將容器目錄中的數據 複製到 數據卷中的_data目錄,然後掛載。

數據卷容器

數據卷可以被掛載到多個容器中,這時候數據卷中的數據被共享。
如果要共享數據卷,需要使用--volumes-from參數。

實驗
docker volume create -d local volume1
vim index.html
    <h1>hello eagle</h1>
docker run -d -it -p 8080:80 -v volume1:/usr/share/nginx/html nginx
docker run -d -it -p 8081:80 --volumes-from a215 nginx      #共享容器a215的數據卷
firewall-cmd --add-port=8080-8081/tcp
firewall-cmd --add-port=8080-8081/tcp --per
  • 測試

訪問http://192.168.191.131:8080/
訪問http://192.168.191.131:8081/
結果一樣則正確

  • 進一步測試
cd /var/lib/docker/volumes/volume1/_data
vim index.html
    <h1>hello world</h1>

訪問http://192.168.191.131:8080/
訪問http://192.168.191.131:8081/
結果由hello eagle變成了hello world


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