Set the working directory for the exec process
In this final step, you will learn how to set the working directory for the command being executed with docker exec
. By default, docker exec
runs commands in the container's configured working directory (often /
). You can override this using the -w
option.
We will continue to use the running ubuntu
container. If it's not running, start it with:
docker run -d ubuntu:latest sleep infinity
Get the Container ID of your running ubuntu
container using docker ps
:
docker ps
Now, let's execute a command that prints the current working directory inside the container. We will use the pwd
command. Replace <container_id>
with your container's ID.
docker exec < container_id > pwd
You should see /
as the output, which is the default working directory in the ubuntu
image.
Now, let's execute the pwd
command again, but this time we will set the working directory to /tmp
using the -w
option.
docker exec -w /tmp < container_id > pwd
Let's look at the new option:
-w /tmp
: This option sets the working directory for the pwd
command to /tmp
inside the container.
You should now see /tmp
as the output. This demonstrates that you can specify a different working directory for the command executed with docker exec
. This is useful when you need to execute commands that operate on files in a specific location within the container.
This concludes the lab on executing commands in Docker containers. You have learned how to start containers for execution, execute commands in running containers, open interactive shell sessions, set environment variables, and set the working directory for exec
processes.