我们可以在 docker 中挂载命名卷的子目录吗?

Can we mount sub-directories of a named volume in docker?

docker-compose 文件 https://docs.docker.com/compose/compose-file/#/volumes-volume-driver 显示了相对于 compose 文件挂载主机子目录的各种方法。

例如:

volumes:
   # Just specify a path and let the Engine create a volume
   - /var/lib/mysql
 
   # Specify an absolute path mapping
   - /opt/data:/var/lib/mysql
 
   # Path on the host, relative to the Compose file
   - ./cache:/tmp/cache
 
   # User-relative path
   - ~/configs:/etc/configs/:ro
 
   # Named volume
   - datavolume:/var/lib/mysql

是否可以在特定位置挂载命名卷的子目录?例如下面这样的东西,我试过了,但似乎不起作用。

# Named volume
  - datavolume/sql_data:/var/lib/mysql

我假设我可以通过将数据卷安装到 /data 之类的位置来管理它,然后在每个容器的 Dockerfile 中,创建从子目录到这些位置的符号链接。

例如在 docker-compose.yml 文件中

volumes:
  - datavolume:/data

然后在容器Dockerfile

RUN ln -s /data/sql_data /var/lib/mysql

我开始沿着这条路走下去,但它变得越来越乱,无法正常工作。在我放弃这种方法或投入时间调试它之前,我想确保没有办法只指定命名卷的子目录。

否,因为 compose/config/config.py#load(config_details) check if datavolume/sql_data matches a named volume (in compose/config/validation.py#match_named_volumes())

datavolume会,datavolume/sql_data不会。

作为 memetech points out ,这是一个自 2017 年 4 月以来跟踪此问题的问题:
moby/moby issue 32582:“[功能] 允许安装命名卷的子目录”。

在那一期中,Joohansson adds (see comment)

In the meantime, I use this workaround to mount the whole volume on a separate path and then symlink it to the sub path.

# In the Dockerfile:
RUN mkdir -p /data/subdir
RUN ln -s /data/subdir /var/www/subdir

Then mount the volume as normal.
The /subdir must exist in the volume.

docker run -d -v myvol:/data mycontainer

Now anything read or written by the webserver will be stored in the volume subdir and can't access the other data.