Working directory set with RUN cd

Declare a working directory with WORKDIR when later instructions need it.

Description

A directory change made by RUN cd ... lasts only within that RUN. Use WORKDIR when later instructions need the same location. Using cd temporarily within one command is valid.

Potential impact

Assuming that the directory change persists can make later commands process files in the wrong location or fail the build.

Remediation

Set the persistent working directory with an absolute WORKDIR path, and check relative paths in subsequent instructions.

Examples

These examples compare working-directory declarations. Both COPY instructions use an absolute destination, so their copy location is unchanged. Set NGINX_IMAGE to a supported NGINX image reference.

Before

dockerfile
ARG NGINX_IMAGE
FROM ${NGINX_IMAGE}

RUN cd /usr/share/nginx/html
COPY index.html /usr/share/nginx/html

After

dockerfile
ARG NGINX_IMAGE
FROM ${NGINX_IMAGE}

WORKDIR /usr/share/nginx/html
COPY index.html /usr/share/nginx/html

References