1.將數據從宿主機掛載到容器中的三種方式
Docker提供三種方式將數據從宿主機掛載到容器中: • volumes:Docker管理宿主機文件系統的一部分(/var/lib/docker/volumes)。保存數據的最佳方式。 • bind mounts:將宿主機上的任意位置的文件或者目錄掛載到容器中。 • tmpfs:掛載存儲在主機系統的內存中,而不會寫入主機的文件系統。如果不希望將數據持久存儲在任何位置,可以使用 tmpfs,同時避免寫入容器可寫層提高性能。
2.Volume
創建卷: docker volume create nginx-vol 查看卷: docker volume ls docker volume inspect nginx-vol 掛載卷: docker run -d -p 89:80 --name=nginx-test --mount src=nginx-vol,dst=/usr/share/nginx/html nginx docker run -d -p 89:80 --name=nginx-test -v nginx-vol:/usr/share/nginx/html nginx 刪除卷: docker rm -f $(docker ps -a |awk '{print $1}') docker rm -f $(docker ps -qa) docker volume rm nginx-vol 注意: 1. 如果沒有指定卷,自動創建。 2. 建議使用--mount,更通用
3.Bind Mounts
用卷創建一個容器: docker run -d -it --name=nginx-test --mount type=bind,src=/app/wwwroot,dst=/usr/share/nginx/html nginx docker run -d -it --name=nginx-test -v /app/wwwroot:/usr/share/nginx/html nginx 驗證綁定: docker inspect nginx-test 清理: docker stop nginx-test docker rm nginx-test 注意: 1. 如果源文件/目錄沒有存在,不會自動創建,會拋出一個錯誤。 2. 如果掛載目標在容器中非空目錄,則該目錄現有內容將被隱藏 [root@localhost ~]# mkdir wwwroot;touch wwwroot/index.html [root@localhost ~]# docker run -d -p 89:80 --mount type=bind,src=$PWD/wwwroot,dst=/usr/share/nginx/html nginx 9c675487b319d6a723f2de35abd09c465aca6472b91e7232a9de6893012f3f63 [root@localhost ~]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 9c675487b319 nginx "nginx -g 'daemon of…" 9 seconds ago Up 8 seconds 0.0.0.0:89->80/tcp sad_robinson [root@localhost ~]# docker exec -it 9c675487b319 bash root@9c675487b319:/# ls /usr/share/nginx/html index.html root@9c675487b319:/# cat /usr/share/nginx/html/index.html root@9c675487b319:/# exit exit [root@localhost ~]# cat wwwroot/index.html [root@localhost ~]# echo "hello" >wwwroot/index.html [root@localhost ~]# docker exec -it 9c675487b319 cat /usr/share/nginx/html/index.html hello [root@localhost ~]# docker rm -f 9c675487b 9c675487b [root@localhost ~]# cat wwwroot/index.html hello [root@localhost ~]#