简体   繁体   English

Docker文件挂载理解

[英]Docker file mount understanding

I'am using docker and I have a strange behaviour when I try to mount a container file on a host file. 我正在使用docker,当我尝试在主机文件上安装容器文件时,我有一个奇怪的行为。

docker run -v /var/tmp/foo.txt:/var/tmp/foo.txt myapp 

The command above runs myapp container which creates a foo.txt file into the /var/tmp directory into the container. 上面的命令运行myapp容器,它将foo.txt文件创建到容器中的/ var / tmp目录中。 Because I need to keep this file on host after myapp dies, I create a mounting point. 因为我需要在myapp死后将此文件保留在主机上,所以我创建了一个安装点。

My problem is that instead of creating foo.txt as a file on host, I end up with an empty directory named "foo.txt" (and nothing inside). 我的问题是,不是在主机上创建foo.txt作为文件,而是最终得到一个名为“foo.txt”的空目录(内部没有任何内容)。

But, if I create an empty text file foo.txt on host and if I run myapp again, it works as expected. 但是,如果我在主机上创建一个空文本文件foo.txt,如果我再次运行myapp,它会按预期工作。

So, my question is, Do I need to create the file on host before starting the container when I use file mount with docker? 所以,我的问题是,当我使用带有docker的文件挂载时,我是否需要在启动容器之前在主机上创建文件?

I think I missed something. 我想我错过了什么。 Thank you for your explanations. 谢谢你的解释。

In fact as you discovered, to mount a host file as a data volume the file must exists otherwise docker will create a directory and mount it. 事实上,正如您所发现的,要将主机文件作为数据卷挂载,文件必须存在,否则docker将创建一个目录并挂载它。

From: https://docs.docker.com/engine/tutorials/dockervolumes/ 来自: https//docs.docker.com/engine/tutorials/dockervolumes/

Mount a host file as a data volume 将主机文件挂载为数据卷

The -v flag can also be used to mount a single file - instead of just directories - from the host machine. -v标志还可用于从主机安装单个文件 - 而不仅仅是目录。

$ docker run --rm -it -v ~/.bash_history:/root/.bash_history ubuntu /bin/bash

Note it never says that the file doesn't exists on host. 请注意,它永远不会说主机上不存在该文件。

As suggested in the comment it is better to mount a directory if you want the container writes into it. 正如评论中所建议的那样,如果您希望容器写入目录,最好安装目录。

Regards 问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM