Course contentsShow
← Cloud and Infrastructure
Lesson 1002 of 2,98920. Docker in DepthFree lesson

RUN: Executing Commands

Master RUN instruction for installing packages, shell vs exec form, and combining commands to reduce layers.

RUN: Executing Commands

You'll learn how to use the RUN instruction to execute commands inside your Docker image during build time—like installing packages or configuring software.

What Is RUN?

The RUN instruction executes commands in a new layer on top of the current image and commits the result. Think of it like taking a base cake (FROM) and adding ingredients one layer at a time—each RUN adds a permanent layer to your final image.

Shell Form vs Exec Form

You can write RUN in two ways:

  • Shell form: RUN apt-get update (runs in /bin/sh -c)
  • Exec form: RUN ["apt-get", "update"] (direct execution, no shell)

Shell form is more common and convenient for chaining commands with && or using shell features like wildcards. Exec form is useful when you need precise control or when no shell is available (like in scratch images).

Combining Commands to Reduce Layers

Every RUN creates a new layer. More layers = larger images and slower builds. Combine related commands using &&:

# Bad: Creates 3 layers
RUN apt-get update
RUN apt-get install -y curl
RUN apt-get clean

# Good: Creates 1 layer
RUN apt-get update && \
    apt-get install -y curl && \
    apt-get clean

This reduces image size and improves caching efficiency because related operations stay together.

When to Use RUN

Use RUN for build-time operations: installing packages, creating directories, downloading files, or compiling code. It's your workhorse for preparing the image environment before runtime.

Key Takeaway: RUN executes commands during image build, creating layers—combine commands with && to minimize layers and keep images lean.