difference between RUN cd and WORKDIR in Dockerfile
Asked Answered
H

1

54

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

Hentrich answered 13/11, 2019 at 23:58 Comment(3)
"It is to mention that WORKDIR / gives me errors" : What errors?Impound
It probably depends on your base Docker image and the other parts of your Dockerfile. For example, I have FROM ubuntu:18.04 and WORKDIR / and it works OK. You need to help us reproduce your problem.Impound
okay thanks ... it's part of another server, it's a bit complicated but I don't know why cd / works but WORKDIR / results in weird errors. I edited my question.Hentrich
H
95

WORKDIR / changes the working directory for future commands.
RUN cd / has no impact on the subsequent RUNs.

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.)

Hispanicize answered 14/11, 2019 at 2:53 Comment(1)
Does absolutely nothingto the subsequent RUNs, not the current one.Psychometrics

© 2022 - 2024 — McMap. All rights reserved.