Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why docker cashes echo date and echo date >> /timestamp.txt

I have docker-compose and Dockerfile:

...
RUN echo date
RUN echo date >> /timestamp.txt
...

and when I delete image and try to create it again I have this message:

#5 [spring-boot-app stage-0 6/9] RUN echo date
#5 CACHED

#6 [spring-boot-app stage-0 7/9] RUN echo date >> /timestamp.txt
#6 CACHED

As I understand docker should not CACHE commands that change result, isn’t it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I try to make command in Dockerfile with random result and expect that docker will not CACHE it.

>Solution :

Docker’s layer caching is based on only two things:

  1. Is the previous layer cached?
  2. If it is, then is this RUN command identical to a previous cached command?

In your example, the RUN command is idempotent: it always creates a file named timestamp.txt containing the single word date. Docker can’t easily tell the difference between that and running date >/timestamp.txt; just running date, which doesn’t affect the container filesystem; or what might happen under the hood running build commands like make.

As a corollary, you should generally arrange your RUN commands so that they are do in fact generate the same result from the same input. Don’t for example RUN git clone, which won’t notice if the upstream repository updates.

COPYing files also affects the layer cache. If the previous layer is cached, then COPYing identical files into the image produces a cached image. This means that if you change something like a package manager lock file (package-lock.json, yarn.lock, mix.lock, go.mod, requirements.txt) it will cause the next RUN command that actually does the installation to be re-run.

In principle you can docker build --no-cache to avoid the layer caching, but this shouldn’t be something you need routinely.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading