On April I wrote a post about Using Docker Multi Stage Builds to build an ASP.NET Core Echo Server and these days while preparing a talk, on CI/CD and kubernetes, I started to play with the simple sample I wrote back then.

Soon enough I noticed that with each docker build command I issued the dependencies for the echoserver were always restored, even if no changes were made to the project file (csproj).

Let see what was going on:

This was the original dockerfile:

 1# This stage builds the application
 2FROM microsoft/dotnet:2.0.6-sdk-2.1.101-jessie AS builder
 3COPY . src
 4WORKDIR src
 5RUN dotnet restore
 6RUN dotnet publish -c release
 7
 8# This stages uses the output from the build
 9FROM microsoft/dotnet:2.0.6-runtime-jessie
10COPY --from=builder src/bin/release/netcoreapp2.0/publish app
11WORKDIR app
12ENV ASPNETCORE_URLS http://*:80
13EXPOSE 80
14ENTRYPOINT ["dotnet", "echoserver.dll"]

As you can see the culprit was between the lines 3 and 5. I was restoring the dependencies after copying all the code! And I fixed it with the following new dockerfile:

 1FROM microsoft/dotnet:2.0.6-sdk-2.1.101-jessie AS builder
 2COPY ./*.csproj ./src/
 3WORKDIR /src
 4RUN dotnet restore
 5COPY . /src
 6RUN dotnet publish -c release
 7
 8FROM microsoft/dotnet:2.0.6-runtime-jessie
 9COPY --from=builder src/bin/release/netcoreapp2.0/publish app
10WORKDIR app
11ENV ASPNETCORE_URLS http://*:80
12EXPOSE 80
13ENTRYPOINT ["dotnet", "echoserver.dll"]

Now the dependencies are restored after copying just the project files (*.csproj) then we copy the rest of the files and build as usual, and yes! with this dockerfile in place the image build times are faster if no dependencies are changed!

Hope it helps!

Feel free to get the code here.