Copying files with execute permissions in Docker Image

Raghav Vaidhyanathan picture Raghav Vaidhyanathan · Jun 12, 2019 · Viewed 8.2k times · Source

Seems like a basic issue but couldnt find any answers so far ..

When using ADD / COPY in Dockerfile and running the image on linux, the default file permission of the file copied in the image is 644. The onwner of this file seems to be as 'root'

However, when running the image, a non-root user starts the container and any file thus copied with 644 permission cannot execute this copied/added file and if the file is executed at ENTRYPOINT it fails to start with permission denied error.

I read in one of the posts that COPY/ADD after Docker 1.17.0+ allows chown but in my case i dont know who will be the non-root user starting so i cannot set the permission as that user.

I also saw another work around to ADD/COPY files to a different location and use RUN to copy them from the temp location to actual folder like what am doing below. But this approach doesnt work as the final image doesnt have the files in /otp/scm

#Installing Bitbucket and setting variables  
WORKDIR /tmp
ADD atlassian-bitbucket-${BITBUCKET_VERSION}.tar.gz .
COPY bbconfigupdater.sh .

#Copying Entrypoint script which will get executed when container starts 
WORKDIR /tmp 
COPY entrypoint.sh .

RUN ls -lrth /tmp

WORKDIR /opt/scm 
RUN pwd && cp /tmp/bbconfigupdater.sh /opt/scm \
 && cp /tmp/entrypoint.sh /opt/scm \
 && cp -r /tmp/atlassian-bitbucket-${BITBUCKET_VERSION} /opt/scm \
 && chgrp -R 0 /opt/ \
 && chmod -R 755 /opt/ \
 && chgrp -R 0 /scm/bitbucket \
 && chmod -R 755 /scm/bitbucket \
 && ls -lrth /opt/scm && ls -lrth /scmdata 

Any help is appreciated to figure out how i can get my entrypoint script copied to the desired path with execute permissions set.

Answer

BMitch picture BMitch · Jun 12, 2019

The default file permission is whatever the file permission is in your build context from where you copy the file. If you control the source, then it's best to fix the permissions there to avoid a copy-on-write operation. Otherwise, if you cannot guarantee the system building the image will have the execute bit set on the files, a chmod after the copy operation will fix the permission. E.g.

RUN chmod +x entrypoint.sh

You do not need to know who will run the container. The user inside the container is typically configured by the image creator (using USER) and doesn't depend on the user running the container from the docker host. When the user runs the container, they send a request to the docker API which does not track the calling user id.

The only time I've seen the host user matter is if you have a host volume and want to avoid permission issues. If that's your scenario, I often start the entrypoint as root, run a script called fix-perms to align the container uid with the host volume uid, and then run gosu to switch from root back to the container user.