Home > Net >  Userid and Group id in docker run command
Userid and Group id in docker run command

Time:03-17

When do we need to add -u $(id -u):$(id -g) in docker run command? I see that it is user id and group ip mapping. But I want to understand this better.

CodePudding user response:

brief docker background

  • Docker starts containers as a root user. The root user has almost full privileged access to the state of the container. Any processes running as that user inherit those permissions.

When do we need user and group

  • It follows that if there’s a bug in one of those processes, it might damage the container. There are ways to limit the damage, but the most effective way to prevent these types of issues is not to use the root user. So we use the group and user.

    RUN groupadd -r -g 2200 example && useradd -rM -g example -u 2200 example

  • Docker supports isolating the USR namespace. By default, user and group IDs inside a container are equivalent to the same IDs on the host machine. When the user namespace is enabled, user and group IDs in the container are remapped to IDs that do not exist on the host.

Hope this help you!

CodePudding user response:

One reason you'd want to run the container under the same UID and GID as your user is so that any files created by the container in the host file system will be owned by you. Take for instance this command, that creates a file called test.txt in the current directory on the host

docker run --rm -v $(pwd):/app ubuntu touch /app/test.txt

In the host file system, that file will be owned by root.

By running the container with the same UID and GID as your user, the file will be owned by you instead

docker run --rm -v $(pwd):/app -u $(id -u):$(id -g) ubuntu touch /app/test2.txt
  • Related