Ron Serruya
Ron Serruya

Reputation: 4446

Docker build-arg doesn't automatically pick up env variable when defined in separate line

Given this Dockerfile:

ARG PY_VERSION

FROM python:${PY_VERSION}-buster

CMD python -V

This docker build . --build-arg PY_VERSION=3.8
and this PY_VERSION=3.8 docker build . --build-arg PY_VERSION work.

But this

PY_VERSION=3.8
echo $PY_VERSION
3.8

docker build . --build-arg PY_VERSION

Sending build context to Docker daemon  2.048kB
Step 1/3 : ARG PY_VERSION
Step 2/3 : FROM python:${PY_VERSION}-buster
invalid reference format

Why doesn't docker pick up the env variable if it's not set in the same line?

versions:
Docker version 19.03.5, build 633a0ea
GNU bash, version 5.0.11(1)-release (x86_64-apple-darwin19.0.0)

Edit:
I'm aware that I can use docker build . --build-arg PY_VERSION=$PY_VERSION, just wondering why the example I provided does not work

Upvotes: 1

Views: 1274

Answers (1)

oxr463
oxr463

Reputation: 1901

In the example provided, you are only declaring PY_VERSION, but you have not assigned it a value.

Per the documentation,

You may also use the --build-arg flag without a value, in which case the value from the local environment will be propagated into the Docker container being built

The built-in env command can be used to display available environment variables.

Per the man page,

If no command name is specified following the environment specifications, the resulting environment is printed. This is like specifying a command name of 'printenv'.

Finally, to set an environment variable, one must use the built-in export command.

Per the man page,

The supplied names are marked for automatic export to the environment of subsequently executed commands.

Upvotes: 1

Related Questions