Rap*_*nah 8 docker docker-compose docker-volume
我在docker-compose.yml文件中看到了Docker卷定义,如下所示:
-v /path/on/host/modules:/var/www/html/modules
Run Code Online (Sandbox Code Playgroud)
我注意到Drupal的官方图片,他们的docker-compose.yml文件使用的是匿名卷.
注意评论:
volumes:
- /var/www/html/modules
- /var/www/html/profiles
- /var/www/html/themes
# this takes advantage of the feature in Docker that a new anonymous
# volume (which is what we're creating here) will be initialized with the
# existing content of the image at the same location
- /var/www/html/sites
Run Code Online (Sandbox Code Playgroud)
有没有办法在容器运行后将匿名卷与主机上的路径相关联?如果没有,拥有匿名卷的重点是什么?
完整的docker-compose.yml示例:
version: '3.1'
services:
drupal:
image: drupal:8.2-apache
ports:
- 8080:80
volumes:
- /var/www/html/modules
- /var/www/html/profiles
- /var/www/html/themes
# this takes advantage of the feature in Docker that a new anonymous
# volume (which is what we're creating here) will be initialized with the
# existing content of the image at the same location
- /var/www/html/sites
restart: always
postgres:
image: postgres:9.6
environment:
POSTGRES_PASSWORD: example
restart: always
Run Code Online (Sandbox Code Playgroud)
匿名卷相当于在镜像的 Dockerfile 中将这些目录定义为 VOLUME。事实上,如果没有明确映射到主机,则在 Dockerfile 中定义为 VOLUME 的目录就是匿名卷。
拥有它们的目的是增加灵活性。
PD:匿名卷已驻留在主机中的 /var/lib/docker (或您配置的任何目录)中的某个位置。要查看它们在哪里:
docker inspect --type container -f '{{range $i, $v := .Mounts }}{{printf "%v\n" $v}}{{end}}' $CONTAINER
注意:替换$CONTAINER为容器的名称。
添加更多信息以回应@JeffRSon的后续问题/评论,询问匿名卷如何增加灵活性,以及从OP回答这个问题:
有没有办法在容器运行后将匿名卷与主机上的路径相关联?如果没有,拥有匿名卷的重点是什么?
TL; DR:您可以通过"数据容器"将特定的匿名卷与正在运行的容器相关联,但这样可以灵活地覆盖现在通过使用命名卷更好地服务的用例.
在Docker 1.9中添加卷管理之前,匿名卷很有用.在此之前,您没有选择命名卷的选项.在1.9版本中,卷成为具有自己生命周期的离散,可管理对象.
在1.9之前,如果没有命名卷的功能,则必须首先创建一个数据容器来引用它
docker create -v /data --name datacontainer mysql
Run Code Online (Sandbox Code Playgroud)
然后将数据容器的匿名卷安装到需要访问卷的容器中
docker run -d --volumes-from datacontainer --name dbinstance mysql
Run Code Online (Sandbox Code Playgroud)
现在,最好使用命名卷,因为它们更易于管理和更明确.
小智 8
如今,匿名卷的一种可能的用例是与绑定挂载结合使用。当您想要绑定某个文件夹但没有任何特定子文件夹时。然后应将这些特定子文件夹设置为命名或匿名卷。它将保证这些子文件夹将出现在容器文件夹中,该文件夹位于容器外部,但您根本不必将其放在主机上的绑定文件夹中。
例如,您可以将前端 NodeJS 项目构建在容器中,其中需要 node_modules 文件夹,但您根本不需要此文件夹来进行编码。然后,您可以将项目文件夹映射到容器外部的某个文件夹,并将 node_modules 文件夹设置为匿名卷。Node_modules 文件夹将始终存在于容器中,即使您的工作文件夹中的主机上没有它。
| 归档时间: |
|
| 查看次数: |
3475 次 |
| 最近记录: |