Docker Copy and change owner

DockerFile PermissionsDockerfile

Docker Problem Overview


Given the following Dockerfile

FROM ubuntu
RUN groupadd mygroup
RUN useradd -ms /bin/bash -G mygroup john
MKDIR /data
COPY test/ /data/test data
RUN chown -R john:mygroup /data
CMD /bin/bash

In my test directory, which is copied I have set the file permissions to 770.

If I do a su john inside my container, I cannot access any of the files or subdirectories in my test directory. It seems this problem is related to the ownership in the aufs filesystem, where the copied directory still is owned by root and permissions are set to 770.

Is there a workaround for this problem to set the permissions correctly? One could be to set the permissions of the original directory to the uid of the container user before copying it. But this seems more like a hack.

Docker Solutions


Solution 1 - Docker

A --chown flag has finally been added to COPY:

COPY --chown=patrick hostPath containerPath

This new syntax seems to work on Docker 17.09.

See the PR for more information.

Solution 2 - Docker

I think I found a solution, which works. Using a data volume container will do the trick. First I create the Data Volume Container, which contains the copy of my external directory:

FROM busybox
RUN mkdir /data
VOLUME /data
COPY /test /data/test
CMD /bin/sh

In my application container, where I have my users, which could look something like this

FROM ubuntu
RUN groupadd mygroup
RUN useradd -ms /bin/bash -G mygroup john
COPY setpermissions.sh /root/setpermissions.sh
CMD /root/setpermissions.sh && /bin/bash

The setpermissions script does the job of setting the user permissions:

#!/bin/bash

if [ ! -e /data/.bootstrapped ] ; then
  chown -R john:mygroup /data
  touch /data/.bootstrapped
fi

Now I just have to use the --volumes-from <myDataContainerId> when running the application container.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChristian MetzlerView Question on Stackoverflow
Solution 1 - DockerGeorgi HristozovView Answer on Stackoverflow
Solution 2 - DockerChristian MetzlerView Answer on Stackoverflow