docker学习笔记(四)docker数据持久化volume
docker數據持久化
官網:https://docs.docker.com/storage/volumes/
docker中的容器是可以隨時銷毀的,容器中的數據會隨著容器的消亡而消亡。然而很多容器都有持久化數據的需求(比方說redis,mysql),為了能夠保存數據以及共享容器間的數據,Docker提出了幾種方式。
Volumes are the preferred mechanism for persisting data generated by and used by Docker containers.?
While bind mounts are dependent on the directory structure of the host machine, volumes are completely managed by Docker.
In addition, volumes are often a better choice than persisting data in a container’s writable layer, because a volume does not increase the size of the containers using it, and the volume’s contents exist outside the lifecycle of a given container.
簡單來說,bind mount和volume其實都是利用的宿主機的文件系統來解決數據的持久化問題,區別在于volume是受docker管理,故而就不需要擔心權限引發的掛載問題,并且目錄路徑是docker自身管理(dockerfile里定義)的,在不同的服務器上會保持目錄的一致性,更方便做遷移等,這也是volume優于bind mount的地方。
volume
-v命令:
-v < unique volume name >:<container directory>: [rw|ro]
第一個參數表示volume name,宿主機上唯一;第二個是container保存數據的目錄,第三個是可選參數
In the case of named volumes, the first field is the name of the volume, and is unique on a given host machine. For anonymous volumes, the first field is omitted.
The second field is the path where the file or directory are mounted in the container.
The third field is optional, and is a comma-separated list of options, such as ro. These options are discussed below.
mysql的數據是掛載在容器內部的/var/lib/mysql目錄下
(1)創建mysql數據庫的container
??docker run -d --name mysql01 -e MYSQL_ROOT_PASSWORD=123456? mysql
(2)查看容器的volume
??docker volume ls
(3)創建一個mysql并為掛載的目錄取一個別名(方便記憶)
docker run -d --name mysql02?-v mysql02_volume:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 mysql
(4)查看容器的volume和mysql02的volume docker volume inspect? volume_name
從這里我們可以看到docker的目錄和容器內的數據存儲目錄的對應關系
在MySQL中創建數據庫,刪除容器后以volume創建一個同樣數據的新容器
刪除容器后,原來的volume仍舊存在(如果想將volume一起刪除,可以使用 docker rm -v container)
通過舊容器的volume創建一個新的容器,也會有和之前的容器一樣的數據
?docker run -d --name mysql03??-v mysql02_volume:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 mysql?
bind mounts
Bind mounts have limited functionality compared to?volumes. When you use a bind mount, a file or directory on the?host machine?is mounted into a container. The file or directory is referenced by its full or relative path on the host machine.?
-v <host directory>: <container directory> :[rw|wo]
bind mounts就是將容器內的某個自定義目錄掛載到宿主機下的某個目錄里,使得用戶可以在宿主機里修改文件,而容器下的文件內容也會隨之發生變化
docker run -d --name mysql04 -v /tmp/test:/usr/local/mysql -e MYSQL_ROOT_PASSWORD=123456 mysql
在宿主機的目錄下新增文件aa.txt,可以在容器內發現掛載的目錄里也多了對應的文件
總結
以上是生活随笔為你收集整理的docker学习笔记(四)docker数据持久化volume的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: docker学习笔记(三)docker中
- 下一篇: docker学习笔记(六)docker-