Docker adduser or useradd

There is something you don’t know about adding users while writing dockerfile
To add a user, use the adduser or useradd command. I don’t know how to specify the password

from ubuntu

run adduser test1
run adduser test2

user test2

cmd ["/bin/sh"]

After doing this, build and run

su test1

If you try to change the user as above, you cannot change the password because you do not know the password.

To summarize, I want to add a user using a Dockerfile and specify a password.

Please share the big picture, as It is not uncommon for inexperienced docker users to ask about specific problems they think must be solved to archive a solution that tries to force “old world patterns” to the container world. A container is not a vm.

Usually you encounter these two variations:

  • an unprivileged user is added in the Dockerfile and either the USER instruction is used to run all following Dockerfile instruction as this user and start the container as this user
  • tools like su-exec or gosu are added to the image and used in the entry point script to start the main process as this unprivileged user during container start. If your container is supposed to do tasks that require root privileges for preparation tasks during start (like chmod/chown), then this is the approach to use.
1 Like

What I want to do is add users using a dockerfile and I specify the passwords for those users myself. The method I used is to create a user using the adduser or useradd command with the run instruction, but I couldn’t specify a password using this.
Other tools are not added and do the above actions in the Ubuntu image. And since the purpose is to study, not to run any special program, what I do may look a little strange.

As @meyay pointed out we usually don’t set passwords in containers. This is why he asked for your use case. We know that you would like to set a password, but not why. The reason could be that you want to use a container as a virtual machine and let people SSH into the container. docker exec lets you define the user that should be used in a container. You can even use UID instead of a username so it works even if there is no user inside the container with that name.

However there are some situations when you need password in a container. For example an application that supports log in with system users without having other methods. This is of course not the best for containers, but if you need, you can set a password using useradd.

useradd --help
# ...
  -p, --password PASSWORD       encrypted password of the new account
# ...

You can pass the password as a secret using buildkit.

I know it is somewhere in the documentation but I couldn’t find it now so I linked a bblogpost that I found.

1 Like

I understood your answer. Thank you for your answer