4.2.5 RUN
A focused guide to RUN, connecting core concepts with practical Docker and container operations.
RUN is the Dockerfile instruction that executes a command inside a temporary container during the build process, capturing whatever filesystem changes that command makes as a new image layer.
Basic Usage
RUN accepts a command to execute, typically used for installing packages, compiling code, or performing any other setup that needs to happen as part of building the image.
RUN apt-get update && apt-get install -y curl
This instruction installs curl inside a temporary container, then commits the resulting filesystem change — the newly installed package — as a new layer.
Shell Form vs. Exec Form
RUN can be written either as a plain string, executed through a shell, or as a JSON array, executed directly without a shell wrapper — a distinction that matters for how shell features like environment variable expansion and piping behave.
RUN apt-get update && apt-get install -y curl
RUN ["apt-get", "update"]
The first form, using a shell, supports operators like &&; the second, exec form, does not, since there is no shell present to interpret them.
Combining Multiple Commands Into a Single RUN
Chaining related commands together within a single RUN instruction, rather than splitting them across multiple instructions, produces a single layer reflecting the combined, net effect, rather than several separate layers.
RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*
This single instruction's layer reflects the final, cleaned-up state, rather than separately layering the installation and a later cleanup step that would not actually reduce the image's overall size.
Caching Behavior of RUN
Each RUN instruction is cached based on the exact text of the command and the state of the image at that point in the build, meaning even a trivial change to the command's text invalidates the cache for that instruction, regardless of whether the actual effect would be identical.
docker build -t myapp .
Why RUN Matters
RUN is the primary mechanism for performing any setup work during a build beyond simply copying files, making it one of the most frequently used and most consequential instructions for determining what an image actually contains and how large it ultimately becomes.