When adding docker support to a ASP.NET Core project VS (15.9.2) will add a default Dockerfile that does restore, build and publish. But instead of just copying all files in
When Docker builds an image, it maintains a build cache:
When building an image, Docker steps through the instructions in your Dockerfile, executing each in the order specified. As each instruction is examined, Docker looks for an existing image in its cache that it can reuse, rather than creating a new (duplicate) image.
Importantly, the ADD
and COPY
instructions get special treatment:
For the
ADD
andCOPY
instructions, the contents of the file(s) in the image are examined and a checksum is calculated for each file. The last-modified and last-accessed times of the file(s) are not considered in these checksums. During the cache lookup, the checksum is compared against the checksum in the existing images. If anything has changed in the file(s), such as the contents and metadata, then the cache is invalidated.
When building a .NET Core solution, we can be sure that after running dotnet restore
, the result of running dotnet restore
again will only change if the .csproj
file has changed (e.g. a new package is added or a version is changed).
By copying the .csproj
files into the image separately, we can take advantage of Docker's build cache, which means that so long as the .csproj
file hasn't changed, the dotnet restore
step will not be re-executed unnecessarily each and every time the image gets rebuilt.