Skip to content
Reinhold Füreder edited this page Mar 27, 2024 · 4 revisions

Use absolute paths, or use WORKDIR to switch to a directory.

Problematic code #1:

FROM busybox
RUN cd /usr/src/app && git clone git@github.com:lukasmartinelli/hadolint.git 

Correct code #1 with WORKDIR (when current working directory should be changed):

FROM busybox
WORKDIR /usr/src/app
RUN git clone git@github.com:lukasmartinelli/hadolint.git

Problematic code #2:

FROM busybox
RUN cd /usr/src/app && cp somedir/somefile ./someDirInUsrSrcApp/

Correct code #2 with absolute paths (when current working directory should not be changed):

FROM busybox
RUN cp somedir/somefile /usr/src/app/someDirInUsrSrcApp/

Rationale:

Only use cd in a subshell. Most commands can work with absolute paths and it in most cases not necessary to change directories. Docker provides the WORKDIR instruction if you really need to change the current working directory, but please mind its "side effects" (see below for more details).

Exceptions:

When executed in a Subshell.

Please note that there may be side effects by the last WORKDIR instruction, as this is also (a) the current working directory when the Docker container is finally started, or (b) the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow it in the Dockerfile (see Dockerfile WORKDIR documentation). Moreover using cd in a RUN instruction also the advantage of being free of side effects afterwards: that is, it only affects this single RUN instruction, but not any subsequent instructions.