Execute a command as a different user
In this step, you will learn how to execute a command inside a running container as a specific user. By default, docker exec
runs commands as the root user inside the container, but you can specify a different user using the -u
or --user
flag. This is important for security and adhering to the principle of least privilege.
Let's continue using the my-nginx
container. First, let's see what user the ls /
command runs as by default.
docker exec my-nginx whoami
The output will likely be root
, as this is the default user for docker exec
.
Now, let's try to execute a command as a different user. The Nginx image typically runs the Nginx process as a non-root user, often named nginx
. Let's try to execute the whoami
command as the nginx
user.
docker exec -u nginx my-nginx whoami
You should see the output nginx
, confirming that the command was executed as the nginx
user.
You can also specify a user ID (UID) instead of a username. To find the UID of the nginx
user inside the container, we can look at the /etc/passwd
file.
docker exec my-nginx cat /etc/passwd | grep nginx
The output will show the entry for the nginx
user, including their UID and GID (Group ID). For example, it might look something like nginx:x:101:101:nginx user,,,:/nonexistent:/bin/false
. In this example, the UID is 101
.
Now, let's execute the whoami
command using the UID. Replace 101
with the actual UID you found in the previous step if it's different.
docker exec -u 101 my-nginx whoami
The output should again be nginx
, demonstrating that you can use either the username or the UID to specify the user for docker exec
.
Executing commands as a non-root user is a good security practice, especially when interacting with sensitive files or performing operations that don't require root privileges.