9

I know docker has a --no-cache=true option to force a clean build of a docker image. For me however, all I'd really like to do is force the last step to run in my dockerfile, which is a CMD command that runs a shell script.

For whatever reason, when I modify that script and save it, a typical docker build will reuse the cached version of that step. Is there a way to force docker not to do so, just on that one portion?

jkj2000
  • 1,563
  • 4
  • 19
  • 26
  • 1
    This has bitten me as well a few times. I've ended up inserting "dummy RUN" entries just to force that final step without invalidating the entire RUN block cache. :( – Marakai May 04 '16 at 01:23

1 Answers1

7

Note that this would invalidate the cache for all Dockerfile directives after that line. This is requested in Issue 1996 (not yet implemented, and now (2021) closed), and issue 42799 (mentioned by ub-marco in the comments).

The current workaround is:

FROM foo
ARG CACHE_DATE=2016-01-01
<your command without cache>

docker build --build-arg CACHE_DATE=$(date) ....

That would invalidate cache after the ARG CACHE_DATE line for every build.

acdcjunior reports in the comments having to use:

docker build --build-arg CACHE_DATE=$(date +%Y-%m-%d_%H:%M:%S)

Another workaround from azul:

Here's what I am using to rebuild in CI if changes in git happened:

export LAST_SERVER_COMMIT=`git ls-remote $REPO "refs/heads/$BRANCH" | grep -o "^\S\+"`
docker build --build-arg LAST_SERVER_COMMIT="$LAST_SERVER_COMMIT"

And then in the Dockerfile:

ARG LAST_SERVER_COMMIT
RUN git clone ...

This will only rebuild the following layers if the git repo actually changed.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • I got error with purely `$(date)` and had to format the it: `... --build-arg CACHE_DATE=$(date +%Y-%m-%d_%H:%M:%S) ...`. – acdcjunior Nov 06 '20 at 20:38
  • 1
    @acdcjunior Thank you for this feedback. I have included your comment in the answer for more visibility. – VonC Nov 06 '20 at 20:49
  • [Issue 1996](https://github.com/moby/moby/issues/1996) is closed for unknown reasons, however [Issue 42799](https://github.com/moby/moby/issues/42799) is open now. – ub_marco Sep 20 '21 at 09:54
  • @ub_marco Thank you. I have amended the answer accordingly. – VonC Sep 20 '21 at 10:46