在很早的一篇帖子里 dockone.io/question/24 就有人问:「请教下代码放在 Docker 里面仍是外面呢」多数人评论相似下面的观点:java
因为开发环境代码一直在变更,并且多人经过 git 协做,因而代码都是放在外面,构建一个运行环境的 image,而后代码部分用 volume 映射进去,方便随时调整。git
个人观点也是这样的,目前我学习的 docker 更多的是本地开发使用,还未到测试或者真实环境下部署的时候,因此我目前赞同将 docker 做为部署开发环境使用,而后将代码和数据库用 volume 映射到容器中。web
因此今天的文章话题是:学习 Docker Volumedocker
A volume is a specially-designated directory within one or more containers that bypasses the Union File System. Volumes are designed to persist data, independent of the container’s life cycle. Docker therefore never automatically delete volumes when you remove a container, nor will it “garbage collect” volumes that are no longer referenced by a container. Also known as: data volume数据库
There are three types of volumes: host, anonymous, and named:tomcat
A host volume lives on the Docker host’s filesystem and can be accessed from within the container.bash
A named volume is a volume which Docker manages where on disk the volume is created, but it is given a name.app
An anonymous volume is similar to a named volume, however, it can be difficult, to refer to the same volume over time when it is an anonymous volumes. Docker handle where the files are stored.webapp
主要有两种参数方式挂载,一种是 -v,另外一种是建立数据卷容器,以--volumes-from 挂载。ide
-v [host-dir]:[container-dir]:[rw|wo]复制代码
其中,
· host-dir:表示主机上的目录,若是不存在,Docker 会自动在主机上建立该目录。
· container-dir:表示容器内部对应的目录,若是该目录不存在,Docker 也会在容器内部建立该目录。
· rw|ro:用于控制卷的读写权限。
因此[host-dir]:[container-dir] 一共就有四种组合,其中 container-dir 有没有存在,先不作尝试考虑。
1、假如不指定 host-dir,咱们看看:
docker run -it -p 8890:8080 --rm -v /usr/local/tomcat/webapps --name test1 tomcat:8.0复制代码
接着使用查看容器中挂载数据卷的状况:
docker inspect test1复制代码
这时候看到的挂载的路径是临时的;而容器中对应的目录,也没有被覆盖:
2、假如指定了 host-dir,咱们来看看:
docker run -it -d -p 8891:8080 --rm -v /Users/ye/docker/learning/javademo/volume2:/usr/local/tomcat/webapps --name test2 tomcat:8.0复制代码
接着使用查看容器中挂载数据卷的状况:
docker inspect test2复制代码
能够看出,将主机本地的文件夹挂在上去了:
这时候咱们能够看到,在容器中对应的目录下的文件,和主机目录下的保持一致了
若是在主机中增长一个文件 world.java,咱们再看看:
保持一致了!
不少时候,咱们会将一些相关的容器部署到同一个主机上,这时候但愿这些容器之间能够共享一些数据。这时,咱们能够建立一个数据卷容器,而后就能够供多个容器挂载使用了。
这里我就不继续往下进行阐述了,由于我学到 Docker Volume 还没真正使用过数据卷容器,因此没有发言权,等我使用过了,我将补充这方面的学习内容。
主要有create、inspect、ls、prune、rm这几个命令,其中拿 ls 举个例子。
List volumes
显示全部数据卷
命令:
docker volume ls [OPTIONS]复制代码
如:
其中:[OPTIONS] 命令:
Name, shorthand | Default | Description |
---|---|---|
--filter, -f | Provide filter values (e.g. ‘dangling=true’) | |
--format | Pretty-print volumes using a Go template | |
--quiet, -q | false | Only display volume names |
具体其它的几个个命令,都比较简单:
Command | Description |
---|---|
docker volume create | Create a volume |
docker volume inspect | Display detailed information on one or more volumes |
docker volume ls | List volumes |
docker volume prune | Remove all unused volumes |
docker volume rm | Remove one or more volumes |
更多参考官网说明:docs.docker.com/engine/refe…
虽然在学习过程当中,发现使用 -v 的挂载方式要多于使用数据卷容器的方式,主要是由于在本地学习为主,或者以单项目开发为主。但在现实产品开发中,我相信用--volume from 的方式会不少,尤为是生产环境下。有待于咱们继续学习,也但愿有人能提点我~~~,万谢!
coding01 期待您关注
也很感谢您能看到这了