I am building an image using Dockfile. I would like to set the Username of the container via the command line to avoid permission issues.
The Dockfile is shown below, I used the variables of USER_NAME
, GROUP_ID
. But when I build, the problem keeps appearing.
The error is: groupadd: option '--gid' requires an argument
I’m guessing that both ${GROUP_ID} and ${USER_NAME} are recognized as empty strings, but shouldn’t they be assigned values when the container is created?
I’ve googled a few examples and based on the examples, I don’t quite see where the problem is?
Please help me!
Thanks!
FROM matthewfeickert/docker-python3-ubuntu:latest
ARG USER_NAME
ARG USER_ID
ARG GROUP_ID
RUN groupadd -r --gid ${GROUP_ID} ${USER_NAME}
RUN useradd --no-log-init -r -g ${GROUP_ID} -u ${USER_ID} ${USER_NAME}
USER ${USER_NAME}
WORKDIR /usr/local/src
2
Answers
You can pass the build args as shown below.
Also, as a best practice consider adding default vales to the args. So if the user doesn’t specify the args the default values will be picked.
When you run the container, you can specify an arbitrary user ID with the
docker run -u
option.This doesn’t require any special setup in the image. The user ID won’t exist in the container’s
/etc/passwd
file but there aren’t really any consequences to this, beyond some cosmetic issues with prompts in interactive debugging shells.A typical use of this is to give your container access to a bind-mounted data directory:
I’d generally recommend not passing a specific user ID into your image build. This would make the user ID "baked in", and if someone with a different host uid wanted to run the image, they’d have to rebuild it.
It’s often a good practice to set up some non-root user, but it doesn’t matter what its user ID is so long as it’s not zero. In turn, it’s also typically a good practice to leave most of your application source code owned by the root user so that the application can’t accidentally overwrite itself.
This setup will still work with the extended
docker run
command shown initially: thedocker run -v
option will cause the container’s/data
directory to take on its numeric uid owner from the host, which (hopefully) matches thedocker run -u
uid.