Search code examples
dockerdocker-multi-stage-build

How to conditionally pull the latest tag of a Docker image, instead of using the cached version?


My Dockerfile contains this line:

COPY --from=whatwg/wattsi:latest /whatwg/wattsi/bin/wattsi /bin/wattsi

i.e., it is copying an executable from the whatwg/wattsi image available on Docker Hub. This is essentially straight out of the documentation on multi-stage builds.

However, once I run the Dockerfile, it caches a local copy of whatwg/wattsi:latest. Then, any subsequent updates of whatwg/wattsi that get pushed to Docker Hub are ignored, and the cached copy is used. (I.e., this entire line just gets skipped, and the layer that it creates is reused.)

The behavior I would like is to have Docker compare the remote whatwg/wattsi:latest to the local cached copy, and re-download if there are differences. Is that possible?

I would like to do this without hard-coding a version for whatwg/wattsi into my Dockerfile, that needs to be updated every time whatwg/wattsi revs.


Solution

  • docker build has a --pull option that will "always attempt to pull a newer version of the image."

    First build (nothing cached)

    Step 2/2 : COPY --from=whatwg/wattsi:latest /whatwg/wattsi/bin/wattsi /bin/watt
    latest: Pulling from whatwg/wattsi
    24f0c933cbef: Pull complete 
    69e2f037cdb3: Pull complete 
    4f7407c4e0dc: Pull complete 
    Digest: sha256:f555e4ff56b88313c7c47ca86b83367f9c1ca93552c477a96b9943e907bb7733
    Status: Downloaded newer image for whatwg/wattsi:latest
     ---> 2ca5d7a1e784
    

    Second build (uses cache)

    Step 2/2 : COPY --from=whatwg/wattsi:latest /whatwg/wattsi/bin/wattsi /bin/watt
     ---> Using cache
     ---> 2ca5d7a1e784
    

    Third build with --pull (checks for updates)

    Step 2/2 : COPY --from=whatwg/wattsi:latest /whatwg/wattsi/bin/wattsi /bin/watt
    latest: Pulling from whatwg/wattsi
    Digest: sha256:f555e4ff56b88313c7c47ca86b83367f9c1ca93552c477a96b9943e907bb7733
    Status: Image is up to date for whatwg/wattsi:latest
     ---> 7d3390252ae1