Docker non root user

- 2 mins read

I have been using dockers since more than last 5 years now. So far I have always launched dockers using the root user, mostly because it is the easiest method of launching a docker. But most of the tasks that I do inside a docker does not require the root user. For example most of the time I launch docker to compile some software. This task should not be done using the root user. Besides files created inside the docker are not accessible by non root user in the host. Hence it is best to create a user with the same userid and groupid as the user launching the docker. The user can be given the sudo permission inside the docker as done in the host environment. The following Dockerfile prepares an image with the user settings.

FROM debian:latest

ARG UID
ARG USER
RUN apt update
RUN apt install sudo
# Add a user
RUN useradd -U -u $UID -m $USER
RUN usermod -a -G sudo $USER
RUN --mount=type=secret,id=password,env=PASSWORD echo ${USER}:${PASSWORD} | chpasswd
# Set the working directory
WORKDIR /home/$USER

# Set the default user
USER $USER

# Run the command
CMD ["/bin/bash"]

Create a file to store the password in the current directory with name password. Here we are creating a file named password to store the password test123.

cat >password<<EOF
test123
EOF

After this we build the docker image and run the docker.

docker build -t debian:bookworm_user --build-arg UID="$UID" --build-arg USER="$USER" --secret id=password,src=./password --build-arg PASSWORD=$PASSWORD .

# Run

docker run --rm -it --name test_user_docker debian:bookworm_user bash