0
0
DockerConceptBeginner · 3 min read

What is ARG in Dockerfile: Simple Explanation and Usage

ARG in a Dockerfile defines a build-time variable that you can pass values to when building an image. It allows you to customize the build process without hardcoding values inside the Dockerfile.
⚙️

How It Works

Think of ARG as a way to give your Dockerfile a question with a blank space that you fill in when you build the image. For example, you might want to choose which version of a software to install without changing the Dockerfile every time.

When you run docker build, you can provide a value for the ARG variable. If you don't, Docker uses the default value if one is set. This makes your Dockerfile flexible, like a recipe where you can swap ingredients easily.

However, ARG values only exist during the build process. They are not saved inside the final image, so they can't be used later when running containers.

💻

Example

This example shows how to use ARG to set a Node.js version during build:

dockerfile
ARG NODE_VERSION=14
FROM node:${NODE_VERSION}

RUN echo "Installing Node.js version $NODE_VERSION"
Output
Installing Node.js version 14
🎯

When to Use

Use ARG when you want to make your Docker image build customizable without changing the Dockerfile. For example:

  • Choosing software versions dynamically
  • Passing secret tokens or keys during build (though be careful as they are visible in build history)
  • Setting environment-specific values like build flags

This helps keep your Dockerfiles clean and reusable across different projects or environments.

Key Points

  • ARG defines build-time variables in Dockerfiles.
  • Values can be passed with docker build --build-arg.
  • They do not persist in the final image.
  • Useful for flexible and reusable Docker builds.

Key Takeaways

ARG allows passing variables during Docker image build for customization.
Build arguments do not remain in the final image and only affect build time.
Use --build-arg flag with docker build to set ARG values.
ARG helps keep Dockerfiles flexible and reusable across environments.