How to create new users in a Docker container?

If you have a docker container and would like to add users to run some processes, this short tutorial is for you. The trick here is to rely on USERADD rather than on the interactive wrapper ADDUSER that many would normally invoke.

Run the command below in your terminal in order to create a home folder for the new docker user. It will ensure also that bash is the shell by default.

RUN useradd -ms /bin/bash the_new_user

Next you can add the following to your Docker file :

USER the_new_user
WORKDIR /home/the_new_user                          [dockerfile create user]

Every interactive session and command afterwards will be executed as user the_new_user:

docker run -t -i image

the_new_user@471w5re87434:~$

In case you would like to grant permissions, you can give the_new_user the required permissions to run your desired programs before executing the user command.

Read: How to run and manage a Docker container on Linux Ubuntu/Debian

For security reasons, the use of non-privileged users inside the Docker containers is recommended. This however has some disadvantages in that people deriving Docker images from your own, would need to switch to root before they can run commands with elevated superuser privileges.


If you like the content, we would appreciate your support by buying us a coffee. Thank you so much for your visit and support.

 

Nikolaus Oosterhof

Nikolaus has a degree in software development. He is passionate about gadgets with a screen, nostalgic for phones, a retired gamer and open source programmer. He likes also to write about macOS and Windows. design web pages and debug long programs!

Leave a Reply

Close Menu