The same file on host and inside container is diff

2019-07-31 07:58发布

I've faced a weird problem: I mount a file from a host to a container in RW mode, then I edit this file on the host but it's not get updated in the container.

This is an extract from docker inspect <container>'s output:

"Mounts": [
    ...
    {
        "Type": "bind",
        "Source": "/home/a_user/projects/drupal/d8-default/composer.json",
        "Destination": "/var/www/d8-default/composer.json",
        "Mode": "rw",
        "RW": true,
        "Propagation": ""
    },
    ...
]

As you may see, the file is mounted as read-write mode as a separate mount. Now when I edit it on the host, it doesn't get changed in the container. I see this by logging into the container and doing simple cat composer.json there and outside of it.

I've performed additional tests with random files and here is what I discovered:

  1. If a file being edited is located in a directory (which is mounted in RW mode) then changes immediately appear in its container's copy.

  2. If a file is mounted directly then changes are not transferred at all, it seems like the container is maintaining its own version of the file!

Indeed it is highly undesired behavior, it breaks my workflows and I haven't found a solution to overcome this disalignment yet. Any suggestions are welcome.

标签: docker
1条回答
【Aperson】
2楼-- · 2019-07-31 08:41

When you mount an individual file into a container, what you are mounting is the inode of the file on the linux filesystem. If you replace the file (which many editors do), then the inode changes. That's not normally an issue if you mount an entire directory because the directory's pointer to the inode gets updated. But when only mounting a single file, writes to the file after starting the container will not be reflected between the inside and outside of the container.

For more details, see this issue: https://github.com/moby/moby/issues/6011


Edit: If your goal is to modify a file outside of the container, and have that modify a single file in a directory of files that can't be in the volume mount, then I'd recommend changing the container to have a symlink to a file in a different directory where you can mount the entire directory instead of a single file. That would look like:

In your Dockerfile:

RUN mkdir -p /var/docker/composer \
 && ln -s /var/docker/composer/composer.json /var/www/d8-default/composer.json

And your volume mount would then be:

docker run -v /home/a_user/projects/drupal/d8-default:/var/docker/composer ...
查看更多
登录 后发表回答