73

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 ?

Max L.
  • 9,774
  • 15
  • 56
  • 86

2 Answers2

124

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.

creack
  • 116,210
  • 12
  • 97
  • 73
  • 47
    The command WORKDIR serves this purpose: http://docs.docker.com/reference/builder/#workdir – Kartoch Oct 06 '15 at 15:09
  • 11
    It would also be neat if `docker build` could throw a warning of some kind when people make this mistake, I just lost a lot of time to this -_- – qntm Feb 15 '16 at 16:13
  • @creack Thanks for the clear explanation - I tried running the docker run commands - they didn't return the CID in my case. Hence I had to use - `docker run ubuntu:latest mkdir tmp123 && CID=$(docker ps --latest --quiet) && ID=$(docker commit $CID ubuntu:test1) ` – Saurabh Hirani Nov 30 '17 at 12:57
  • can `WORKDIR ` run inside `RUN` cmd? – alper Apr 21 '22 at 21:46
  • It works when put n same RUN command 'RUN cd path && pwd' – serkan Dec 28 '22 at 11:25
30

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
Serp C
  • 864
  • 1
  • 10
  • 24
Lidong Guo
  • 2,817
  • 2
  • 19
  • 31