Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker : RUN cd ... does not work as expected [duplicate]

Tags:

docker

The following Dockerfile :


FROM ubuntu:12.10
RUN mkdir tmp123
RUN cd tmp123
RUN pwd

has the output :


Uploading context 10240 bytes
Step 1 : FROM ubuntu:12.10
 ---> b750fe79269d
Step 2 : RUN mkdir tmp123
 ---> Running in d2afac8a11b0
 ---> 51e2bbbb5513
Step 3 : RUN cd tmp123
 ---> Running in 4762147b207c
 ---> 644801121b92
Step 4 : RUN pwd
 ---> Running in 3ed1c0f1049d
/
 ---> eee62a068585

when built (docker build command)

it appears that RUN cd tmp123 has no effect

why ?

like image 787
Max L. Avatar asked Jul 26 '13 22:07

Max L.


People also ask

Is Workdir same as CD?

Show activity on this post. RUN cd / does absolutely nothing. WORKDIR / changes the working directory for future commands. Each RUN command runs in a new shell and a new environment (and technically a new container, though you won't usually notice this).

Does Docker copy overwrite existing file?

It seems that docker build won't overwrite a file it has previously copied. I have a dockerfile with several copy instructions, and files touched in earlier COPY directives don't get overwritten by later ones. After building this, $BASE/config/thatfile. yml contains the contents of file1.

Can we have 2 CMD in Dockerfile?

There can only be one CMD instruction in a Dockerfile. If you list more than one CMD then only the last CMD will take effect. If CMD is used to provide default arguments for the ENTRYPOINT instruction, both the CMD and ENTRYPOINT instructions should be specified with the JSON array format.

How do I change the working directory in a Docker container?

Easy ! Just use the WORKDIR command to change the directory you want to. Any other commands you use beyond this command will be executed in the directory you have set. It is also a better practice to make use of WORKDIR in docker.


2 Answers

It is actually expected.

A dockerfile is nothing more but a wrapper on docker run + docker commit.

FROM ubuntu:12.10
RUN mkdir tmp123
RUN cd tmp123
RUN pwd

Is the same thing as doing:

CID=$(docker run ubuntu:12.10 mkdir tmp123); ID=$(docker commit $CID)
CID=$(docker run $ID cd tmp123); ID=$(docker commit $CID)
CID=$(docker run $ID pwd); ID=$(docker commit $CID)

Each time you RUN, you spawn a new container and therefore the pwd is '/'.

If you feel like it, you can open an issue on github in order to add a CHDIR instruction to Dockerfile.

like image 72
creack Avatar answered Nov 23 '22 16:11

creack


Maybe you can try this; I am not sure and I can't try it. If it does not work, I hope you don't downvote.

Just:

RUN 'cd tmp123 ; pwd'

Instead of

RUN cd tmp123
RUN pwd
like image 24
Lidong Guo Avatar answered Nov 23 '22 17:11

Lidong Guo