dockerdockerfilepipeline

Conditional check in Dockerfile


I have a Dockefile, in which I want to copy certain files based on input environment variable. So far I have tried the following. I am able to verify that my environment variable is passed correctly. During my docker build I get the following error -->> /bin/sh: COPY: not found

ARG arg=a
RUN if [ "$arg" = "a" ] ; then \
 echo arg is $arg; \
 COPY test.txt /
else \
 echo arg is $arg; \
fi

Solution

  • What you are essentially trying to do here is to have a COPY command inside a RUN command.

    Dockerfiles don't have nested commands.

    Moreover, a RUN command runs inside an intermediate container built from the image. Namely, ARG arg=a will create an intermediate image, then docker will spin up a container, and use it to run the RUN command, and commit that container as the next intermediate image in the build process.

    so COPY is not something that can run inside the container, and in fact RUN basically runs a shell command inside the container, and COPY is not a shell command.

    AFAICT dockerfiles don't have any means of doing conditional execution. The best you can do is:

    COPY test.txt
    RUN if [ "$arg" = "a" ] ; then \
     echo arg is $arg; \
    else \
     echo arg is $arg; \
     rm -r test.txt \
    fi
    

    But keep in mind that if test.txt is a 20GB file, the size of your image will still be > 20GB.