1、【已验证】docker -v 挂载会以宿主机情况为准,如果容器路径有文件将被丢失并以宿主机路径为准;
因此可以先启动镜像把路径文件拷出来到宿主机
参考:nginx docker主页说明 https://hub.docker.com/_/nginx
Complex configuration
$ docker run --name my-custom-nginx-container -v /host/path/nginx.conf:/etc/nginx/nginx.conf:ro -d nginx
For information on the syntax of the nginx configuration files, see the official documentation (specifically the Beginner's Guide).
If you wish to adapt the default configuration, use something like the following to copy it from a running nginx container: // 意思是正式运行docker之前,先把容器路径文件放到宿主机,再正式使用挂载启动
$ docker run --name tmp-nginx-container -d nginx
$ docker cp tmp-nginx-container:/etc/nginx/nginx.conf /host/path/nginx.conf
$ docker rm -f tmp-nginx-container
2、【已验证,但不代表全部情况(vm上跑docker)】映射文件会因为宿主机生成文件同名的路径 而失败,可以先在宿主机生成同名文件(vm上跑docker不行) 或者 使用“1、”的解决方案;
【已溯源】Use bind mounts
https://docs.docker.com/storage/bind-mounts/
Differences between -v
and --mount
behavior
Because the -v
and --volume
flags have been a part of Docker for a long time, their behavior cannot be changed. This means that there is one behavior that is different between -v
and --mount
.
If you use -v
or --volume
to bind-mount a file or directory that does not yet exist on the Docker host, -v
creates the endpoint for you. It is always created as a directory.
If you use --mount
to bind-mount a file or directory that does not yet exist on the Docker host, Docker does not automatically create it for you, but generates an error.