Docker and --userns-remap, how to manage volume permissions to share data between host and container?

后端 未结 3 1561
甜味超标
甜味超标 2020-11-29 15:29

In docker, files created inside containers tend to have unpredictable ownership while inspecting them from the host. The owner of the files on a volume is root (uid 0) by de

3条回答
  •  鱼传尺愫
    2020-11-29 16:06

    You can avoid permission problems by using the docker cp command.

    Ownership is set to the user and primary group at the destination. For example, files copied to a container are created with UID:GID of the root user. Files copied to the local machine are created with the UID:GID of the user which invoked the docker cp command.

    Here is your example switched to use docker cp:

    $ docker run -ti -v /data debian:jessie /bin/bash
    root@e33bb735a70f:/# echo 'hello' > /data/test.txt
    root@e33bb735a70f:/# exit
    exit
    $ docker volume ls
    DRIVER              VOLUME NAME
    local               f073d0e001fb8a95ad8d919a5680e72b21a457f62a40d671b63c62ae0827bf93
    $ sudo ls -l /var/lib/docker/100000.100000/volumes/f073d0e001fb8a95ad8d919a5680e72b21a457f62a40d671b63c62ae0827bf93/_data
    total 4
    -rw-r--r-- 1 100000 100000 6 Oct  6 10:34 test.txt
    $ docker ps -a
    CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS                          PORTS               NAMES
    e33bb735a70f        debian:jessie       "/bin/bash"         About a minute ago   Exited (0) About a minute ago                       determined_hypatia
    $ docker cp determined_hypatia:/data/test.txt .
    $ ls -l test.txt 
    -rw-r--r-- 1 don don 6 Oct  6 10:34 test.txt
    $ cat test.txt
    hello
    $ 
    

    However, if you just want to read files out of a container, you don't need the named volume. This example uses a named container instead of a named volume:

    $ docker run -ti --name sandbox1 debian:jessie /bin/bash
    root@93d098233cf3:/# echo 'howdy' > /tmp/test.txt
    root@93d098233cf3:/# exit
    exit
    $ docker cp sandbox1:/tmp/test.txt .
    $ ls -l test.txt
    -rw-r--r-- 1 don don 6 Oct  6 10:52 test.txt
    $ cat test.txt
    howdy
    $ 
    

    I find named volumes useful when I want to copy files into a container, as described in this question.

提交回复
热议问题