DEV Community

Cover image for Reduce Your Docker Image Build Time
Gerade Geldenhuys
Gerade Geldenhuys

Posted on

4

Reduce Your Docker Image Build Time

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay