Skip to content

Dockerfile RUN command chaining

Dockerfile RUN command chaining is the practice of combining multiple shell commands into a single RUN instruction within a Dockerfile.^[600-developer-docker-dockerfile-docker-ssh.md] Instead of writing each command as a separate layer, commands are chained together, typically using control operators like && or ;, to execute sequentially in one layer.

Rationale

In Dockerfile optimization, a best practice is to minimize the number of layers by merging related commands^[600-developer-docker-dockerfile-docker-ssh.md]. For example, system package management operations—such as updating the package list and installing software—should be performed in a single RUN statement.^[600-developer-docker-dockerfile-docker-ssh.md]

This approach prevents the creation of unnecessary intermediate layers (filesystem layers) and ensures that the package cache or temporary files created by the first command are available to the subsequent command in the sequence, which is particularly useful for reducing the final image size.^[600-developer-docker-dockerfile-docker-ssh.md]

Syntax and Structure

In a chained RUN command, each distinct command is placed on a new line, typically ending with the control operator &&.^[600-developer-docker-dockerfile-docker-ssh.md] The backslash \ character is used at the end of the line to indicate that the command continues on the following line.^[600-developer-docker-dockerfile-docker-ssh.md]

This structure improves the readability of the Dockerfile, making it clear that multiple steps are part of a single logical layer or stage of the build process^[600-developer-docker-dockerfile-docker-ssh.md].

Example

The following example demonstrates how to update the package list, install openssh-server, and create a directory in a single layer^[600-developer-docker-dockerfile-docker-ssh.md]:

RUN apt-get update && \
    apt-get install -y openssh-server && \
    mkdir -p /var/run/sshd

Sources

^[600-developer-docker-dockerfile-docker-ssh.md]