0
0
DockerConceptBeginner · 3 min read

What is RUN in Dockerfile: Explanation and Usage

The RUN instruction in a Dockerfile executes commands inside the image during build time, creating a new layer with the results. It is used to install software, update packages, or configure the image before it is finalized.
⚙️

How It Works

The RUN instruction works like a step in a recipe where you perform an action that changes the state of your image. Imagine you are baking a cake and adding ingredients one by one; each RUN command adds or changes something inside the image, like installing a program or creating files.

When Docker builds the image, it executes each RUN command in a temporary container. After the command finishes, Docker saves the changes as a new layer in the image. This layering helps Docker reuse parts of the image if nothing changed, making builds faster.

Because RUN commands happen during build time, their effects are permanent in the image and available when you later run a container from that image.

💻

Example

This example shows how to use RUN to update package lists and install curl in an Ubuntu-based image.

dockerfile
FROM ubuntu:22.04
RUN apt-get update && apt-get install -y curl
CMD ["curl", "--version"]
Output
curl 7.81.0 (x86_64-pc-linux-gnu) libcurl/7.81.0 OpenSSL/3.0.2 zlib/1.2.12 Release-Date: 2022-04-06 Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smb smbs smtp smtps telnet tftp Features: AsynchDNS HTTPS-proxy IPv6 Largefile NTLM NTLM_WB SSL TLS-SRP UnixSockets
🎯

When to Use

Use RUN when you need to prepare your image by installing software, setting up tools, or modifying files before the container runs. For example, you might install a web server, add libraries, or compile code.

It is best to combine related commands in one RUN to reduce image layers and keep the image size smaller. For instance, updating packages and installing software can be done in a single RUN line.

Remember, RUN commands happen only once during build, so they are not for commands you want to run every time the container starts.

Key Points

  • RUN executes commands during image build, creating new image layers.
  • It is used to install software or change the image state permanently.
  • Commands run in a temporary container and their results are saved.
  • Combine commands in one RUN to optimize image size.
  • RUN is not for runtime commands; use CMD or ENTRYPOINT for that.

Key Takeaways

RUN executes commands during Docker image build to modify the image.
It creates a new layer with the changes made by the command.
Use RUN to install software or prepare the image before running containers.
Combine multiple commands in one RUN to reduce image layers and size.
RUN commands do not run when the container starts; use CMD or ENTRYPOINT for that.