I have a Python package called mypackage
that I want to install in a Docker image. I want to create a user called myuser
in the image instead of just running things as root. Here is my Dockerfile.
# syntax=docker/dockerfile:1
FROM python:3
# Create a user.
RUN useradd --user-group --system --no-log-init --create-home myuser
RUN chown -R myuser:myuser /home/myuser
USER myuser
# Install the package.
RUN python -m pip install --upgrade pip
WORKDIR /home/myuser
COPY . ./mypackage
RUN pip install /home/myuser/mypackage && rm -rf /home/myuser/mypackage
This fails on the pip install
because myuser
does not have write permissions in the /home/myuser
folder. If I build the image without the last step and then go look at the directory permissions everything is still owned by root.
$ ls -l
total 4
drwxr-xr-x 3 root root 4096 Aug 16 14:21 mypackage
I assume the mistake is with the chown
statement, but I copied that logic from another Stack Overflow answer and it looks right to me.
What am I doing wrong?
Specify the user:group in the COPY command, see https://docs.docker.com/engine/reference/builder/#copy
COPY [--chown=<user>:<group>] <src>... <dest>
COPY [--chown=<user>:<group>] ["<src>",... "<dest>"]
The fixed Dockerfile:
FROM python:3
# Create a user.
RUN useradd --user-group --system --no-log-init --create-home myuser
USER myuser
# Install the package.
RUN python -m pip install --upgrade pip
WORKDIR /home/myuser
COPY --chown=myuser:myuser . ./mypackage
RUN pip install /home/myuser/mypackage && rm -rf /home/myuser/mypackage