Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between RUN cd and WORKDIR in Dockerfile

Tags:

In terms of the way Docker works, is there any difference between RUN cd / and WORKDIR / inside a Dockerfile?

like image 968
Hossein Kalbasi Avatar asked Nov 13 '19 23:11

Hossein Kalbasi


People also ask

What does Workdir mean in Dockerfile?

The WORKDIR command is used to define the working directory of a Docker container at any given time. The command is specified in the Dockerfile. Any RUN , CMD , ADD , COPY , or ENTRYPOINT command will be executed in the specified working directory.

What is the difference between run and CMD in Dockerfile?

RUN is an image build step, the state of the container after a RUN command will be committed to the container image. A Dockerfile can have many RUN steps that layer on top of one another to build the image. CMD is the command the container executes by default when you launch the built image.

Can we use CD in Dockerfile?

1 Answer. 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.

Can we have multiple Workdir in Dockerfile?

you can have multiple WORKDIR in same Dockerfile. If a relative path is provided, it will be relative to the previous WORKDIR instruction. If no WORKDIR is specified in the Dockerfile then the default path is / . The WORKDIR instruction can resolve environment variables previously set in Dockerfile using ENV.


Video Answer


1 Answers

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). The ENV and WORKDIR directives before it affect how it starts up. If you have a RUN step that just changes directories, that will get lost when the shell exits, and the next step will start in the most recent WORKDIR of the image.

FROM busybox WORKDIR /tmp RUN pwd       # /tmp  RUN cd /      # no effect, resets after end of RUN line RUN pwd       # still /tmp  WORKDIR / RUN pwd       # /  RUN cd /tmp && pwd  # /tmp RUN pwd       # / 

(For the same reason, RUN export doesn't do anything that outlives the current Dockerfile instructions, and RUN . or the non-standard RUN source won't cause environment variables to be set.)

like image 76
David Maze Avatar answered Oct 03 '22 13:10

David Maze