How to add users to Docker container?
The trick is to use useradd
instead of its interactive wrapper adduser
.I usually create users with:
RUN useradd -ms /bin/bash newuser
which creates a home directory for the user and ensures that bash is the default shell.
You can then add:
USER newuserWORKDIR /home/newuser
to your dockerfile. Every command afterwards as well as interactive sessions will be executed as user newuser
:
docker run -t -i imagenewuser@131b7ad86360:~$
You might have to give newuser
the permissions to execute the programs you intend to run before invoking the user command.
Using non-privileged users inside containers is a good idea for security reasons. It also has a few drawbacks. Most importantly, people deriving images from your image will have to switch back to root before they can execute commands with superuser privileges.
Ubuntu
Try the following lines in Dockerfile
:
RUN useradd -rm -d /home/ubuntu -s /bin/bash -g root -G sudo -u 1001 ubuntuUSER ubuntuWORKDIR /home/ubuntu
useradd
options (see: man useradd
):
-r
,--system
Create a system account. see: Implications creating system accounts-m
,--create-home
Create the user's home directory.-d
,--home-dir HOME_DIR
Home directory of the new account.-s
,--shell SHELL
Login shell of the new account.-g
,--gid GROUP
Name or ID of the primary group.-G
,--groups GROUPS
List of supplementary groups.-u
,--uid UID
Specify user ID. see: Understanding how uid and gid work in Docker containers-p
,--password PASSWORD
Encrypted password of the new account (e.g.ubuntu
).
Setting default user's password
To set the user password, add -p "$(openssl passwd -1 ubuntu)"
to useradd
command.
Alternatively add the following lines to your Dockerfile
:
SHELL ["/bin/bash", "-o", "pipefail", "-c"]RUN echo 'ubuntu:ubuntu' | chpasswd
The first shell instruction is to make sure that -o pipefail
option is enabled before RUN
with a pipe in it. Read more: Hadolint: Linting your Dockerfile.
To avoid the interactive questions by adduser, you can call it with these parameters:
RUN adduser --disabled-password --gecos '' newuser
The --gecos
parameter is used to set the additional information. In this case it is just empty.
On systems with busybox (like Alpine), use
RUN adduser -D -g '' newuser
See busybox adduser