What is RUN in Dockerfile: Explanation and Usage
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.
FROM ubuntu:22.04 RUN apt-get update && apt-get install -y curl CMD ["curl", "--version"]
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
CMDorENTRYPOINTfor that.