Docker Community Forums

Share and learn in the Docker community.

Userns-remap with useradd during build

Hi all,
userns-remap is set up like this
host_user:1000:1
host_user:100000:65536

And in my Dokerfile(which based on ubuntu:bionic) there is a line, which creates a new user
RUN useradd -m container_user
So UID of container_user inside of the container is 1000.

Since the user was created, owner of container_user’s home directory is root. And I do not understand why.
root@8cb31067da78:/home/container_use# ll
total 24
drwxr-xr-x 1 root root 4096 Sep 23 08:27 ./
drwxr-xr-x 1 root root 4096 Sep 23 08:27 …/
-rw-r–r-- 1 root root 220 Apr 4 2018 .bash_logout
-rw-r–r-- 1 root root 3771 Apr 4 2018 .bashrc
-rw-r–r-- 1 root root 807 Apr 4 2018 .profile

If I remove first line in /etc/subuid, or make the range from 1001, it starts working as I expecting(at least, owner of /home/container_user (inside of the container) become the container_user.
Could someone explain, why owner of /home/container_user is root when UID of the container_user is 1000? :slight_smile:

If you can prearrange users and groups in advance, then it’s possible to assign UIDs and GIDs in such specific way so that host users correspond to namespaced users inside containers.

Here’s an example (Ubuntu 14.04, Docker 1.10):

Create some users with fixed numeric IDs:

useradd -u 5000 ns1

groupadd -g 500000 ns1-root
groupadd -g 501000 ns1-user1

useradd -u 500000 -g ns1-root ns1-root
useradd -u 501000 -g ns1-user1 ns1-user1 -m
Manually edit auto-generated subordinate ID ranges in /etc/subuid and /etc/subgid files:

ns1:500000:65536
(note there are no records for ns1-root and ns1-user1 due to MAX_UID and MAX_GID limits in /etc/login.defs)

Enable user namespaces in /etc/default/docker:

DOCKER_OPTS="–userns-remap=ns1"
Restart daemon service docker restart, ensure /var/lib/docker/500000.500000 directory is created.

Now, inside containers you have root and user1, and on the host – ns1-root and ns1-user1, with matching IDs

UPDATE: to guarantee that non-root users have fixed IDs in containers (e.g. user1 1000:1000), create them explicitly during image build.

Test-drive:

Prepare a volume directory

mkdir /vol1
chown ns1-root:ns1-root /vol1
Try it from a container

docker run --rm -ti -v /vol1:/vol1 busybox sh
echo “Hello from container” > /vol1/file
exit
Try from the host

passwd ns1-root
login ns1-root
cat /vol1/file
echo “can write” >> /vol1/file
Not portable and looks like a hack, but works.

Thanks for the answer.Your solution looks working. I’m gonna actually keep it in mind, but the question was why that works as that works within the presented configuration