How to Pass Build Arg During Build in Docker
To pass a build argument during a Docker build, use the
--build-arg flag with docker build and define the argument in your Dockerfile with ARG. This lets you send values to the build process that can customize the image.Syntax
The syntax to pass a build argument during Docker image build involves two parts:
- Dockerfile: Use
ARG <name>to declare the argument. - Build command: Use
docker build --build-arg <name>=<value> .to pass the value.
This allows the Dockerfile to use the argument value during the build.
dockerfile
ARG <name>
# Example usage in Dockerfile
RUN echo "The value is $<name>"Example
This example shows how to pass a build argument named VERSION to a Docker image build and use it inside the Dockerfile.
dockerfile
FROM alpine:3.18 ARG VERSION RUN echo "Building version: $VERSION" > /version.txt CMD cat /version.txt
Example
Build the Docker image passing the VERSION argument:
bash
docker build --build-arg VERSION=1.2.3 -t myapp:1.2.3 . docker run --rm myapp:1.2.3
Output
Building version: 1.2.3
Common Pitfalls
- Not declaring
ARGin the Dockerfile before using--build-argcauses the argument to be ignored. - Build arguments are not environment variables at runtime; they only exist during build.
- Using
ENVafterARGcan make the value available at runtime if needed.
dockerfile
### Wrong: Passing build-arg without ARG declaration # Dockerfile FROM alpine RUN echo "$VERSION" # Build command # docker build --build-arg VERSION=1.0 . ### Right: Declare ARG # Dockerfile FROM alpine ARG VERSION RUN echo "$VERSION" # Build command # docker build --build-arg VERSION=1.0 .
Quick Reference
Summary tips for passing build arguments in Docker:
- Always declare
ARGin Dockerfile before using the argument. - Pass values with
--build-arg name=valueduringdocker build. - Build args are only available during build, not at container runtime.
- Use
ENVif you want to keep the value in the final image environment.
Key Takeaways
Use
ARG in Dockerfile to declare build arguments before using them.Pass build argument values with
--build-arg name=value during docker build.Build arguments exist only during build and are not available at container runtime.
Combine
ARG and ENV to pass values from build time to runtime if needed.Always test your Dockerfile to ensure build arguments are correctly passed and used.