Search code examples
dockercachingcomposition

Rebuild a docker image depending on the output of a command


Say I want to rebuild my docker image when a new compiler version is available in some repository.

I can gather the version inside the container:

FROM centos:7
RUN yum info gcc | grep Version | sort | tail -1 | cut -d: -f2 | tr -d ' '

If I build this container and tag it as base, I can use that information and setup a second container:

FROM base
RUN yum install gcc-4.8.5

Docker will be able to cache the second container and not rebuild it, when the compiler version has not changed. But creating that requires some shell scripting and that might be brittle in, e.g., a continuous integration scenario.

What I would like to do is to introduce a unified source for these two containers. Is there a way to write something like this:

FROM centos:7
$GCC_VERSION=RUN yum info gcc | grep Version | sort | tail -1 | cut -d: -f2 | tr -d ' '
RUN yum install gcc-$GCC_VERSION

and have the variables expanded (and the commands still cached) during docker build ?


Solution

  • You can use the ARG instruction. Build args affect the cache in the way you want to: Impact on build caching

    With a Dockerfile like this:

    FROM centos:7
    ARG GCC_VERSION
    RUN yum install -y gcc-$GCC_VERSION
    

    The image gets only rebuilt if the GCC_VERSION changes.

    docker build --build-arg GCC_VERSION=$(docker run centos:7 yum info gcc | grep Version | sort | tail -1 | cut -d: -f2 | tr -d ' ') .