1

When adding a Docker support, Visual Studio generates a Dockerfile which looks like that:

#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
WORKDIR /app
EXPOSE 80

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

FROM build AS publish
RUN dotnet publish "MyApp.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "MyApp.dll"]

I have a question regarding the lines

COPY ["MyApp/MyApp.csproj", "MyApp/"]
RUN dotnet restore "MyApp/MyApp.csproj"
COPY . .

As far as I understand, the first two lines copy just the csproj to the docker image and use it to restore dependencies. The third line in turn copies the whole solution folder content.

Copying of the whole solution is probably done to ensure the publishing process completes successfully in case it needs something outside of the project folder itself (is this a correct assumption?).

More importantly, why only copy only csproj first instead of copying the whole solution and running restore after? In other words, why not do this:

COPY . .
RUN dotnet restore "MyApp/MyApp.csproj"
2
  • Docker images are created using layers. One layer for each command in the dockerfile. If no changes have been made, the layer can be reused in a later build. By doing it this way, the restore step can reuse an older layer as long as you haven't changed the project file. If you do it the way you propose, the restore has to be done every time you change anything in your C# code. Jun 21, 2021 at 18:28
  • Thanks, @HansKilian! Please post this as an answer so I can mark as a solution.
    – alexalok
    Jun 21, 2021 at 18:30

1 Answer 1

2

Docker images are created using layers. One layer for each command in the dockerfile. If no changes have been made, the layer can be reused in a later build. By doing it this way, the restore step can reuse an older layer as long as you haven't changed the project file. If you do it the way you propose, the restore has to be done every time you change anything in your C# code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.