dockerpermissionschown

Docker permissions with base image for non-root user


I have a base image that does a couple of installments with root permission, then create a new user, change owner of the WORKDIR then switch to the user. The child image will inherit this image with FROM and run its Python task as user.

#base image

FROM scratch
WORKDIR /master

RUN adduser ...

RUN chown user:group -R .
USER user:group

These two images will have different WORKDIR, where the child image's WORKDIR is the sub directory of the base image, created during image build.

#child image

FROM base-image
WORKDIR /master/worker

...

RUN pip install -e .

When building the child image, the last pip command got an error, it can not create new files because lack of permission

error: could not create 'python_project.egg-info': Permission denied

Apparently, the command chown in base image only grant permission to user for base image WORKDIR, not including newly created sub-directory in the child image's WORKDIR.

If I create master/worker during base image build then change owner, the child image works, because the user is now owner of both /master and /master/worker

#base image

...

MKDIR worker
RUN chown user:group -R .
USER user:group

But I prefer not to do this, since there might be more different WORKDIR created from other child images.

Is there any way I can grant permission to sub-directory in child image from the base image (that does not exist yet in there)? The chown -R flag doesn't work in this case.


Solution

  • I found the solution, just simply create the subfolder before setting it as WORKDIR in child image

    RUN mkdir worker
    WORKDIR /master/worker