1

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

Ron Serruya
  • 3,988
  • 1
  • 16
  • 26

1 Answers1

1

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.

oxr463
  • 1,573
  • 3
  • 14
  • 34
  • But docker should pick it automatically from the env variable, see the comments to the question, it works with `export` – Ron Serruya Dec 30 '19 at 11:32
  • Exactly, until you `export` the variable it has not been defined within the local context. – oxr463 Dec 30 '19 at 11:37