Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the current working directory for docker exec with an internal bash shell?

Tags:

bash

docker

I have a developer docker image based on ubuntu:14.04 that I use to develop apps for Ubuntu 14.04. I start this image when the machine boots with docker start image-name

My home directory was bind mounted with --volumes when initially created.

To enter the image I have an alias defined in .bash_aliases

alias d_enter="docker exec -ti ub1404-dev /bin/bash" 

So to enter the image I just type d_enter

But I often forget to run d_enter after entering a long path and would like d_enter to switch to that internal directory automatically.

The following doesn't work.

docker exec -ti ub1404-dev /bin/bash <(echo ". ~/.bashrc && cd $(pwd)") 

Is there another way I could achieve the desired result?

For example, if my current working directory is: /home/matt/dev/somepath/blabla

And I type d_enter, my current working directory currently becomes: /home/matt what I want to do for current directory after exec is be /home/matt/dev/somepath/blabla

like image 278
hookenz Avatar asked Sep 02 '15 02:09

hookenz


People also ask

How can I run a docker EXEC command inside a docker container?

Running Commands in an Alternate Directory in a Docker Container. To run a command in a certain directory of your container, use the --workdir flag to specify the directory: docker exec --workdir /tmp container-name pwd.

How do I bash inside a docker container?

In order to start a Bash shell in a Docker container, execute the “docker exec” command with the “-it” option and specify the container ID as well as the path to the bash shell. If the Bash is part of your PATH, you can simply type “bash” and have a Bash terminal in your container.

How do I mount my current working directory to my docker container in Windows?

Open Settings on Docker Desktop (Docker for Windows). Select Shared Drives. Select the drive that you want to use inside your containers (e.g., C). Click Apply.


Video Answer


2 Answers

From API 1.35+ you can use the -w (--workdir) option:

docker exec -w /my/dir container_name command 

https://docs.docker.com/engine/reference/commandline/exec/

like image 164
Lucas Basquerotto Avatar answered Oct 05 '22 23:10

Lucas Basquerotto


You can achieve it with:
docker exec -it containerName sh -c "cd /var/www && /bin/bash"

like image 22
Aung Kyaw Nyunt Avatar answered Oct 06 '22 00:10

Aung Kyaw Nyunt