03 / 10

What does the RUN instruction do in dockerfile?

The RUN instruction executes commands in a new layer on top of the current image and commits the results, permanently incorporating the changes into the image.

The RUN instruction is one of the primary workhorse commands in a Dockerfile, responsible for executing commands during the image build process. Each RUN command creates a new layer in the image, capturing the filesystem changes made by the command as a permanent part of the image. This is fundamentally different from CMD and ENTRYPOINT, which define what happens when a container runs—RUN commands shape the image itself by installing packages, configuring software, creating directories, or any other build-time setup required for your application.

RUN Instruction Examples

The RUN instruction has two forms: shell form and exec form. The shell form (RUN command param1 param2) invokes the command through /bin/sh -c, which provides shell processing like variable substitution and command chaining. The exec form (RUN ["executable", "param1", "param2"]) executes the command directly without shell processing, which is more precise and avoids shell string munging. The exec form is particularly useful when running on base images without /bin/sh or when you need exact control over command arguments.

Important Considerations
  1. 1

    Each RUN instruction creates a new image layer, so chaining multiple commands with && is recommended to reduce the number of layers and final image size .

  2. 2

    Commands in RUN are executed at build time, not when the container runs, making them ideal for installation and configuration that shouldn't change .

  3. 3

    The working directory for RUN commands can be set with the WORKDIR instruction, which affects all subsequent RUN, CMD, COPY, and ADD instructions .

  4. 4

    Environment variables set with ENV are available during RUN execution, allowing dynamic configuration based on build arguments .

  5. 5

    Commands that create large temporary files or caches should clean up in the same RUN instruction to avoid bloating the final image .