1

After creating a container in docker

docker run -it -d --name my-container my-image

I want to execute a command as specific user (according to docker exec)

docker exec -it --user my-user my-container echo $USER

But this outputs root

How can I execute a command as specific user in docker container?

2 Answers 2

3

Quite apart from the whether the user exists in the docker container, I think you should also understand when $USER is resolved. When you run this command in your shell:

docker exec -it --user my-user my-container echo $USER

The string $USER is replaced with root before even calling upon the docker executable. (I'm assuming you're running it as as root, otherwise I've no idea where it's from.)

To avoid this, you'd have to escape the $, like this:

docker exec -it --user my-user my-container echo \$USER

When I tested this, the value of $USER was not known to the shell inside the container. If you want to see that the user running inside the container is indeed your user, try this:

docker exec -it --rm --user my-user my-container /bin/id -u

That will print the userid of my-user. Unfortunately, that user won't exist until you create it in the container, so it doesn't have a name. Another person has already posted a link in this question to address that.

0

Look at this stackoverflow post. You need to create the user in the docker image if you want to use it during the runtime

1
  • My image has the user already, I can start a bash shell with my-user through docker exec -it --user my-user my-container bin/bash. This enters bash as user my-user.
    – fabda01
    Aug 16, 2018 at 19:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.