others-How to run docker container using root user?

1. Purpose

In this post, I would demonstrate how to run docker container as root user.



2. The solution

2.1 The final solution

TL;DR, here is the final solution to this problem, Let’s say there is a docker container whose id is 58f193740e99, then we can enter the container as root user:

[[email protected] ~]# docker exec --user root -it 58f193740e99 sh
/ # whoami
root



2.2 How does docker map user from container to host?

In docker, each container can have a different user and group id, e.g., a specific internal user can be used to execute the program in the container instead of a user that exists on the host system. Each container can have the highest-privileged root account, but it is not in the same namespace as the host . By using an isolated user namespace, security can be improved and the processes in the container can be prevented from acquiring additional permissions; at the same time, different users can also be used to further control permissions in the container.

The best way to prevent privilege-escalation attacks from within a container is to configure your container’s applications to run as unprivileged users. For containers whose processes must run as the root user within the container, you can re-map this user to a less-privileged user on the Docker host. The mapped user is assigned a range of UIDs which function within the namespace as normal UIDs from 0 to 65536, but have no privileges on the host machine itself.

The remapping itself is handled by two files: /etc/subuid and /etc/subgid. Each file works the same, but one is concerned with the user ID range, and the other with the group ID range. Consider the following entry in /etc/subuid:

testuser:231072:65536

How to specify user in Dockerfile, here is an example:

FROM ubuntu:latest
RUN useradd -r -u 1001 -g myuser myuser
USER myuser
ENTRYPOINT [“sleep”, “infinity”]

You can see that we just created a user named myuser in group myuser in Dockerfile.

You can read more about user remapping in docker by reading this document.



2.3 What does --user xxx do in docker ?

As the official document shows, the docker exec --user format is:

--user , -u		Username or UID (format: <name|uid>[:<group|gid>])



3. Summary

In this post, I demonstrated how to switch user in docker container, the key point is to use the docker exec --user command and options to switch users . That’s it, thanks for your reading.

-->