When building Docker images, it would be awesome if we could mount/point to the cached feed of NuGet packages we have on our developer machines, but since that is not possible, Docker goes and downloads all packages for a project from NuGet every time we run Docker build. That’s if we don’t make use of caching our packages every time we update our dependencies.
To cache our dependencies when building our Docker images, update your Dockerfile to the following:
COPY *.csproj .
RUN dotnet restore
# Copy everything else and build
COPY . .
RUN dotnet publish -c Release -o out
Applying the small change above will ensure that our package cache is generated the first time we build our image. Thereafter, the cache will be used in subsequent builds. Unless we change our dependencies in the project the cache will remain valid and speed up our compilation time. When using this approach my build time went from around 1 minute to +- 5 seconds.
Other useful tips
Some other tips at your disposal to reduce your image build times are the popular techniques of using a Docker ignore file, to exclude everything you don’t want in your image while also reducing its size, and using multistage builds, of which I’m sure you are already doing.
I hope this neat little trick that packs a punch comes in handy for you as it did for me.
Thanks for reading.
Top comments (0)