How to pass arguments to a Dockerfile?
Asked Answered
M

2

296

I am using RUN instruction within a Dockerfile to install a rpm

RUN yum -y install samplerpm-2.3

However, I want to pass the value "2.3" as an argument. My RUN instruction should look something like:

RUN yum -y install samplerpm-$arg

where $arg=2.3

Magavern answered 13/12, 2015 at 17:42 Comment(0)
S
428

As of Docker 1.9, You are looking for --build-arg and the ARG instruction.

Check out this document for reference. This will allow you to add ARG arg to the Dockerfile and then build with

docker build --build-arg arg=2.3 .
Stumpy answered 13/12, 2015 at 18:28 Comment(3)
After doing all that, I am getting an error **No package samplerpm-$arg available. ** It seems the argument value of 2.3 is not getting substituted.Magavern
what about env variables instead?Di
Environment variables are a runtime variable. The build arguments are a build time variable. The distinction here is declaring variables that you only want to use for building the image and do not want (or should not) store for runtime of the container.Stumpy
P
7

If you have multiple FROM statements in dockerfile, make sure to redeclare the variable/s with no value for each variable/s or they'll be lost when it exits the block.

Here's an article that writes more about this: Why are my Docker ARGs empty?

Here's an example:

ARG VERSION=latest
FROM ubuntu:${VERSION}

ARG VERSION
ARG FILENAME
COPY ${FILENAME} /home/ubuntu/${FILENAME}
Pucida answered 8/9, 2023 at 11:51 Comment(1)
Note that since VERSION isn't reused (in the fragment shown), you don't actually need to repeat "ARG VERSION" after the FROM statement.Carmody

© 2022 - 2024 — McMap. All rights reserved.