Search code examples
dockerdocker-composedockerfiledocker-build

In a Docker Build with the build-arg flag,values are not getting passed correctly


I am using the following command in a shell script to pass the docker args

docker build -t "${IMAGE_INPUT}-temp" --build-arg BASE_IMAGE=$IMAGE_INPUT --build-arg TEMP_DIR=$TEMP -f $DOCKER_FILE .

and my docker file has the following content

ARG BASE_IMAGE
ARG TEMP_DIR
FROM $BASE_IMAGE

RUN echo $TEMP_DIR && \
    echo $BASE_IMAGE

but both the variables print as null here despite passing values in the docker build command. After assigning default values it works but without default values the variable values are going as null.

Could someone please help as to how can i pass multiple args and use those args in my dockerfile


Solution

  • Every FROM instruction in a Dockerfile instructs docker to start a new Stage and by default there is no context propagated from one stage to the next. You could think of each stage as it's an independent image build. More on multi-staged docker image builds and why they were introduced can be found in the docs here.

    In your case this means that you are declaring the build arg BASE_IMAGE and TEMP_DIR in the first stage (in this case stage 0) of your docker build. However your echo command is in the second stage of your docker build and therefore doesn't know anything about these build args (they are scoped to stage 0).

    To solve this issue you can just declare your build args in every stage they are needed. This should work fine:

    # start of stage 0
    ARG BASE_IMAGE
    
    FROM $BASE_IMAGE
    
    # start of stage 1
    ARG BASE_IMAGE
    ARG TEMP_DIR
    
    RUN echo $TEMP_DIR && \
        echo $BASE_IMAGE