Create users in Dockerfile as following:
Running docker container as a root user is risky because the root user in containers has same uid 0 as the host root user. So you have to change the user in containers to non-root user as possible.
Most simple and effective way is to create a user in Dockerfile
. For example:
You can also change the user with -u
option of docker run
. With Kubernetes, you can use SecurityContext to modify the user.
This Dockerfile
is fine, but useradd
has many options. Let me describe which options should be used in Dockerfile.
Options often used with Dockerfile are:
Let’s review each option.
-g
specifies uid. Because the same gid as uid is easy to understand, you should use -g
.-l
looks good because lastlog and faillog have few meanings.-m
to create home directory. If not, use -M
.-r
option makes user as a system account. uid is configured from /etc/login.defs
and home directory doesn’t be created. You should not use this option because you will use -u
to specify uid and use -m/-M
to configure home directory.-s /bin/false
can forbid remote login. You can execute shell with docker exec -u $uid sh
, even if /bin/false
or /bin/nologin
is set. This option might protect from direct remote login, so you should use -s /bin/false
.-u
specifies uid. When -u
was not used, uid is assigned automatically. To manage simply, you should use this option.-U
creates a group named same as the user but gid can differ from uid. -g
is preferred to -U
.In conclusion, you should use following instructions to create users:
If you need home directory:
Because major distributions reserve uid from 1000 to 60000, I proposed 61000 as uid. By the way, worker nodes of GKE reserve uid from 5000 to 60000. If you use 5000 as uid, they conflict.
For example, you often use bundle exec rails console
. ↩