CodeBlanks Logo Icon CodeBlanks

The RUN instruction

Learn to run commands at build time with RUN.

The RUN instruction

RUN runs a command during the build and adds the result to the image as a new layer. It is used for installing packages, compiling and creating directories:

FROM ubuntu:24.04
RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*

update and install must be in the same RUN; written separately, the install may use a stale cached package list. The trailing rm shrinks the layer by deleting the package lists.

Layer count and size

Each RUN is a separate layer. A file downloaded in one layer and deleted in the next doesn't shrink the image, since the earlier layer doesn't change. That is why installing and cleaning up are done in the same RUN:

# bad: 3 layers, cache files stay in the image
RUN apt-get update
RUN apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/*

# good: a single layer
RUN apt-get update \
    && apt-get install -y --no-install-recommends curl \
    && rm -rf /var/lib/apt/lists/*

Practice Installing in one layer

Write a Dockerfile based on ubuntu:24.04; chain apt-get update, apt-get install -y curl git and rm -rf /var/lib/apt/lists/* with && in a single RUN instruction.

Starter code

terminal
# buraya yaz

Sample solution

terminal
FROM ubuntu:24.04
RUN apt-get update && apt-get install -y curl git && rm -rf /var/lib/apt/lists/*

Expected output

[+] Building 4.2s (8/8) FINISHED
 => naming to docker.io/library/tools:latest done

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the difference between RUN and CMD?

  • RUN only works on Linux
  • CMD runs several times
  • RUN runs during the build, CMD when the container starts Correct answer
  • They are the same

Explanation: RUN changes the image; CMD only records the default start command.

2 Install a package without asking for confirmation.

Question
RUN apt-get update && apt-get install ____ curl
Answer
RUN apt-get update && apt-get install -y curl

Explanation: The build is non-interactive; -y confirms the prompts automatically.

3 Match.

Term Meaning
RUN Adds a new layer
&& Chains commands in one RUN
\ (end of line) Continues the line
rm -rf /var/lib/apt/lists/* Shrinks the layer

All lessons in Beginner