Abimbola Esuruoso
Abimbola Esuruoso

Reputation: 4197

Docker Run and variable substitution

I have a variable in a script called image_name

image_name="my-app"

And I am attempting to pass this variable to a docker container as seen below:

docker build -t $image_name .
docker run --rm --name $image_name -e "app_dir=${image_name}" $image_name

But this variable is not set and is blank within the context of the docker build

This is a snippet from the Dockerfile below:

....

RUN     echo dir is $app_dir

....

This is a snippet of the build output below:

....

Step 2 : RUN echo dir is $app_dir
---> Running in db93a939d701
dir is
---> c9f5e2a657d5
Removing intermediate container db93a939d701

....

Anyone know how to do the variable substitution?

Upvotes: 8

Views: 9450

Answers (2)

Luís Bianchin
Luís Bianchin

Reputation: 2486

Notice that you are using the variable inside the Dockerfile. That variable will be evaluated at build time (docker build), so you need to pass its value at that moment. That can be achieved with the --build-arg param.

Changing your example, it would be:

docker build --build-arg app_dir=${image_name} -t $image_name .
docker run --rm --name $image_name $image_name

Upvotes: 3

Abimbola Esuruoso
Abimbola Esuruoso

Reputation: 4197

This is achievable using the build-arg parameter of the docker build command

See: https://github.com/docker/docker/issues/6822#issuecomment-168170031 for an example

Upvotes: 1

Related Questions