Search code examples
dockerdockerfiledocker-build

Using --build-arg to modify FROM clause in Docker image


Say we have a Dockerfile like so:

FROM node:9

and we build it with:

docker build -t foo .

my question is - is there a way to change the FROM clause using a --build-arg, something like this:

ARG NODE_VERSION
FROM node:$NODE_VERSION

and the build that with:

docker build -t foo --build-arg NODE_VERSION="8" .

Solution

  • It works exactly like you have proposed. Given the following Dockerfile:

    ARG base_image=alpine
    FROM $base_image
    

    I can build it like this and get an Alpine based image:

    docker build -t test1 .
    

    Or like this to get a Fedora based image:

    docker build -t test2 --build-arg base_image=fedora .
    

    As you say, changing the base image would invalidate the cache.