File ownership after docker cp

前端 未结 4 2077

How can I control which user owns the files I copy in and out of a container?

The docker cp command says this about file ownership:

The cp

4条回答
  •  眼角桃花
    2021-02-19 23:40

    In addition to @Don Kirkby's answer, let me provide a similar example in bash/shell script for the case that you want to copy something into a container while applying different ownership and permissions than those of the original file.

    Let's create a new container from a small image that will keep running by itself:

    docker run -d --name nginx nginx:alpine
    

    Now wel'll create a new file which is owned by the current user and has default permissions:

    touch foo.bar
    ls -ahl foo.bar
    >> -rw-rw-r-- 1 my-user my-group 0 Sep 21 16:45 foo.bar
    

    Copying this file into the container will set ownership and group to the UID of my user and preserve the permissions:

    docker cp foo.bar nginx:/foo.bar
    docker exec nginx sh -c 'ls -ahl /foo.bar'
    >> -rw-rw-r--    1 4098     4098           0 Sep 21 14:45 /foo.bar
    

    Using a little tar work-around, however, I can change the ownership and permissions that are applied inside of the container.

    tar -cf - foo.bar --mode u=+r,g=-rwx,o=-rwx --owner root --group root | docker cp - nginx:/
    docker exec nginx sh -c 'ls -ahl /foo.bar'
    >> -r--------    1 root     root           0 Sep 21 14:45 /foo.bar
    

    tar options explained:

    • c creates a new archive instead of unpacking one.
    • f - will write to stdout instead of a file.
    • foo.bar is the input file to be packed.
    • --mode specifies the permissions for the target. Similar to chown, they can be given in symbolic notation or as an octal number.
    • --owner sets the new owner of the file.
    • --group sets the new group of the file.

    docker cp - reads the file that is to be copied into the container from stdin.

    This approach is useful when a file needs to be copied into a created container before it starts, such that docker exec is not an option (which can only operate on running containers).

提交回复
热议问题