What's the default user for docker exec?
The default user in docker exec is the same user used to start the container which can be set in docker run or your compose file.
If you do not explicitly set the user when starting the container, it will default to the user configured in the image, you can inspect the image to look this up. This is configured by the last USER line in the Dockerfile. It may also be configured by a parent image specified by the FROM line.
If neither the image, nor the run command specifies a user, docker defaults to root
, uid 0.
Does a USER line in the Dockerfile affect the default user for docker exec?
Yes, as the docs mention:
The USER instruction sets the user name (or UID) and optionally the user group (or GID) to use when running the image and for any RUN, CMD and ENTRYPOINT instructions that follow it in the Dockerfile.
Here's an example Dockerfile which creates a user and makes that as the run user.
cat Dockerfile
FROM ubuntu:latest
RUN useradd -r sathya
USER sathya
Build the image
docker build -t sathya:user .
Sending build context to Docker daemon 19.46kB
Step 1/3 : FROM ubuntu:latest
---> 113a43faa138
Step 2/3 : RUN useradd -r sathya
---> Running in 5b72508a891d
Removing intermediate container 5b72508a891d
---> b81692196e13
Step 3/3 : USER sathya
---> Running in d43d399a86ac
Removing intermediate container d43d399a86ac
---> c0388a898992
Successfully built c0388a898992
Successfully tagged sathya:user
Run a container
docker run -it -d sathya:user bash
0903e85fa4de4bb820f015f3ff2bbca9eb2c038814ff7ea809519334687597c7
Exec the container. See that the running user is the default user specified
docker exec -it 0903e85fa4de bash
sathya@0903e85fa4de:/$ whoami
sathya