Sometimes, when we would like to use arguments to build our Docker image from Docker files, we could use --build-arg to build the Docker image dynamically.
In this blog post, I am going to show how we could use --build-arg to dynamically select Docker base images and the caveats of doing so.
Example
Dockerfile
We have prepared a Dockerfile build-args.Dockerfile. The content of the Dockerfile is as follows.
We could see that there are actually two scopes for the arguments. _UBUNTU_VERSION would not be available after the base image was built. But _UBUNTU_VERSION was definitely available before the base image was built because the image was “Ubuntu 18.04.2 LTS” which was exactly the same as our default value.
With --build-arg provided, we could see that the default argument values had been overwritten. However, _UBUNTU_VERSION, which was defined before the base image was built, was still not available after the base image was built.
Conclusions
Be aware of the scope of Docker building arguments.