HiveBrain v1.2.0
Get Started
← Back to all entries
patterndockerMinor

Change owner of files created inside a Docker container without changing the Dockerfile

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
ownerwithoutthecontainercreateddockerdockerfilefileschangingchange

Problem

When I create a file inside a container with docker-compose run web touch test the file owns to root:root. I want to change it to be $USER without to use chown.

I'm aware of the --user option but it requires to have the user created on the Dockerfile. I prefer to not change the Dockerfile because it is committed on a git repo and I don't want to commit this because it is kind of personal config.

I tried to mount the file /etc/passwd but the user is not present when we run a command. I can use su $USER -c "..." but there is some issues with this.

So, what's the best way to set create new files with the owner set as the user of the host machine?

Solution

No need to change the Dockerfile. Just define a certain user, e.g. jenkins and a certain uid, e.g. 1000 and ensure the same uid is used when a folder is mounted.

ARG user=jenkins
ARG uid=1000

# Jenkins is run with user `jenkins`, uid = 1000
# If you bind mount a volume from the host or a data container,
# ensure you use the same uid
RUN mkdir -p $JENKINS_HOME \
    && chown ${uid}:${gid} $JENKINS_HOME \
    && addgroup -g ${gid} ${group} \
&& adduser -h "$JENKINS_HOME" -u ${uid} -G ${group} -s /bin/bash -D ${user}

RUN chown -R ${user} "$JENKINS_HOME" /usr/share/jenkins/ref


https://github.com/jenkinsci/docker/blob/master/Dockerfile-alpine

Code Snippets

ARG user=jenkins
ARG uid=1000

# Jenkins is run with user `jenkins`, uid = 1000
# If you bind mount a volume from the host or a data container,
# ensure you use the same uid
RUN mkdir -p $JENKINS_HOME \
    && chown ${uid}:${gid} $JENKINS_HOME \
    && addgroup -g ${gid} ${group} \
&& adduser -h "$JENKINS_HOME" -u ${uid} -G ${group} -s /bin/bash -D ${user}

RUN chown -R ${user} "$JENKINS_HOME" /usr/share/jenkins/ref

Context

StackExchange DevOps Q#4190, answer score: 5

Revisions (0)

No revisions yet.