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"
restorestep 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.