Search code examples
c#.netasp.net-corevisual-studio-2017dockerfile

Why do we build and publish as two steps when publish also builds?


Sorry if this is a stupid question, but why does the dockerfile include steps to build and publish when the publish also builds?

The following Dockerfile is created in my web application:

FROM microsoft/dotnet:2.1-aspnetcore-runtime AS base
WORKDIR /app
EXPOSE 80

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

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

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

Solution

  • According to the book .NET Microservices: Architecture for Containerized .NET Applications (Microsoft EBook), the first build instruction is redundant because the publish instruction also builds, and it is right after the first build instruction. Page 94 (86), line 10.

    Here is a short excerpt from the book:

    1 FROM microsoft/dotnet:2.1-aspnetcore-runtime AS base
    2 WORKDIR /app
    3 EXPOSE 80
    4
    5 FROM microsoft/dotnet:2.1-sdk AS build
    6 WORKDIR /src
    7 COPY src/Services/Catalog/Catalog.API/Catalog.API.csproj …
    8 COPY src/BuildingBlocks/HealthChecks/src/Microsoft.AspNetCore.HealthChecks …
    9 COPY src/BuildingBlocks/HealthChecks/src/Microsoft.Extensions.HealthChecks …
    10 COPY src/BuildingBlocks/EventBus/IntegrationEventLogEF/ …
    11 COPY src/BuildingBlocks/EventBus/EventBus/EventBus.csproj …
    12 COPY src/BuildingBlocks/EventBus/EventBusRabbitMQ/EventBusRabbitMQ.csproj …
    13 COPY src/BuildingBlocks/EventBus/EventBusServiceBus/EventBusServiceBus.csproj …
    14 COPY src/BuildingBlocks/WebHostCustomization/WebHost.Customization …
    15 COPY src/BuildingBlocks/HealthChecks/src/Microsoft.Extensions …
    16 COPY src/BuildingBlocks/HealthChecks/src/Microsoft.Extensions …
    17 RUN dotnet restore src/Services/Catalog/Catalog.API/Catalog.API.csproj
    18 COPY . .
    19 WORKDIR /src/src/Services/Catalog/Catalog.API
    20 RUN dotnet build Catalog.API.csproj -c Release -0 /app
    21
    22 FROM build AS publish
    23 RUN dotnet publish Catalog.API.csproj -c Release -0 /app
    24
    25 FROM base AS final
    26 WORKDIR /app
    27 COPY --from=publish /app
    28 ENTRYPOINT ["dotnet", "Catalog.API.dll"]
    

    For the final optimization, it just happens that line 20 is redundant, as line 23 also builds the application and comes, in essence, right after line 20, so there goes another time-consuming command.