File ownership on building docker images

2019-05-01 04:25发布

问题:

I want to set up file permissions for files I add to a docker image. I have this simple Dockerfile:

FROM ubuntu:utopic

WORKDIR /app
RUN groupadd -g 1000 baz && useradd -u 1000 -g baz baz -d /app -s /bin/false
RUN chown baz:baz /app && chmod g+s /app
# want this to be have group baz
ADD foo /app/

Building this with docker build -t abc . where there is a foo file in . creates an image. However, the permissions on /app/foo inside is not what I want.

docker run abc ls -la     
total 12
drwxr-xr-x  2 baz  baz  4096 Sep  2 23:21 .
drwxr-xr-x 37 root root 4096 Sep  3 07:27 ..
-rw-rw-r--  1 root root  419 Sep  2 21:43 foo

Note that file foo doesn't belong to group baz despite the setgid bit being set on the /app dir. I could use RUN chown -R baz:baz /app after adding the files, but that casues the a copy of the layer to be created (Note the size of the two layers below):

docker history abc | head -n 3
IMAGE               CREATED              CREATED BY                                      SIZE                COMMENT
b95a3d798873        About a minute ago   /bin/sh -c chown -R baz:baz /app                419 B               
7e007196c116        About a minute ago   /bin/sh -c #(nop) ADD file:2b91d9890a9c392390   419 B   

Is there some way to get around this and have the ownership of files added be what I want?

回答1:

Instead of adding foo directly, you could pack it as a tar-archive and set permissions for a specific UID/GID. Here is a post on how to do it: https://unix.stackexchange.com/questions/61004/force-the-owner-and-group-for-the-contents-of-a-tar-file

After that you can just untar it within your Docker image (ADD untars automagically). You should see the permissions preserved without an additional layer.