Use an ARG in Dockerfile FROM for dynamic image specification

Dockerfiles have been able to use ARGs to allow passing in parameters during a docker build using the CLI argument --build-arg for some time. But until recently (Docker's 17.05 release, to be precise), you weren't able to use an ARG to specify all or part of your Dockerfile's mandatory FROM command.

But since the pull request Allow ARG in FROM was merged, you can now specify an image / repository to use at runtime. This is great for flexibility, and as a concrete example, I used this feature to allow me to pull from a private Docker registry when building a Dockerfile in production, or to build from a local Docker image that was created as part of a CI/testing process inside Travis CI.

To use an ARG in your Dockerfile's FROM:

ARG MYAPP_IMAGE=myorg/myapp:latest

Then if you want to use a different image/tag, you can provide it at runtime:

docker build -t container_tag --build-arg MYAPP_IMAGE=localimage:latest .

If you don't specify --build-arg, then Docker will use the default value in the ARG.

Typically, it's preferred that you set the FROM value in the Dockerfile itself—but there are many situations (e.g. CI testing) where you can justify making it a runtime argument.


That's actually really helpful for dynamic tagging an building with GitLab CI for branch-dependend tags :)

Thanks very much. We use scripts to build our docker images and dynamically inject the FROM variable for different env's (ie. dev/staging/prod all have different FROM) so this is very great

I have similar usecase
can you please share your dockerfile how you have managed to do so
we are building base image and saving to aws ecr then from aws ecr but want to add from each aws account id and here i need help how i can write dockerfile FROM so it will take base image stored in each account dev stage and prod

What if you want to pass a build tag from a docker-compose file to Dockerfile?