In terms of the way Docker works, is there any difference between RUN cd /
and WORKDIR /
inside a 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.
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.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With