2

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

4

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.

Sign up to request clarification or add additional context in comments.

Comments

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 Comment

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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.