'how does Docker associate cache layers to a particular dockerfiles?

Let's say I have this docker file in a folder which is in D: drive, so the path is D:\MyProjects\webapp

FROM mcr.microsoft.com/dotnet/sdk:3.1
WORKDIR /src
COPY ["webapp/WebApplication.csproj", "webapp/"]
RUN dotnet restore "webapp/WebApplication.csproj"
COPY . .
WORKDIR "/src/webapp"
RUN dotnet build "WebApplication.csproj" -c Release -o /app/build

I know docker use cache layers so the second time you build the image, if nothing changes, then docker will use cache layers to speed up the build time.

But I could have another folder/drive(C:\Projects\webapp) also contains the same name of webapplication (different source code), then how does Docker know which is the right cache layer to use? or does Docker records the location of Dockerfile? if docker does this, then if I move a folder to another driver, then docker will lose all the cache layers?



Solution 1:[1]

The location of the dockerfile is not important for the caching strategy.

The caching strategy is based on the files checksum.

Edit: let me give an example

Imagine a dockerfile:

FROM ubuntu:latest
COPY src/ /var/www
RUN php /var/www/setup.php

Docker works by creating layers. This dockerfile will generate a 3 layers image:

  • Layer 1: the ubuntu:latest itself. This layer is named with the checksum of all files in the image
  • Layer 2: will add to the previous layer the /var/www folder with contents of src folder. The layer again will be named using the checksum of all image files.
  • Layer 3: the setup command will change some files, and again the differences will be checksummed.

Note that docker doesn't cares about what's outside, just what's inside (that might be reflect of outside)

So if you have two dockerfile with same content used in different contexts, the files copied to the image will be different and consequently the checksum too, so it will not confuse your context A with B.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1