通过编辑你向项目添加 Docker 支持时 Visual Studio 生成的 Dockerfile,可以自定义容器映像。 无论你是从 Visual Studio IDE 生成自定义容器,还是设置命令行生成,都需要了解 Visual Studio 是如何使用 Dockerfile 生成项目的。 你需要了解此类详细信息,因为出于性能方面的考虑,Visual Studio 在生成和运行容器化应用时遵循一个特殊的流程,而这在 Dockerfile 中并不明显。
使用多阶段生成功能,可以在生成中间映像的阶段创建容器映像。 例如,考虑一个典型的 Dockerfile。 第一个阶段在 Visual Studio 生成的 Dockerfile 中称为 base,尽管这些工具并不需要该名称。
# This stage is used when running from VS in fast mode (Default for Debug configuration)
FROM mcr.microsoft.com/dotnet/aspnet:3.1-buster-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
Dockerfile 中的行以 Microsoft Container Registry (mcr.microsoft.com) 中的 ASP.NET 映像开头,创建可公开端口 80 和 443 的中间映像 base,并将工作目录设置为 /app。
下一阶段是 build,其显示如下:
# This stage is used to build the service project
FROM mcr.microsoft.com/dotnet/sdk:3.1-buster-slim AS build
WORKDIR /src
COPY ["WebApplication43/WebApplication43.csproj", "WebApplication43/"]
RUN dotnet restore "WebApplication43/WebApplication43.csproj"
COPY . .
WORKDIR "/src/WebApplication43"
RUN dotnet build "WebApplication43.csproj" -c Release -o /app/build
# This stage is used to publish the service project to be copied to the final stage
FROM build AS publish
RUN dotnet publish "WebApplication43.csproj" -c Release -o /app/publish
# This stage is used in production or when running from VS in regular mode (Default when not using the Debug configuration)
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "WebApplication43.dll"]
最后阶段再次从 base 开始,并包括 COPY --from=publish 以将发布的输出复制到最终映像中。 由于无需包含 sdk 映像中的所有生成工具,因此此过程可以使最终映像小得多。
下表总结了 Visual Studio 创建的典型 Dockerfile 中使用的阶段:
阶段
说明
base
创建发布生成应用所在的基本运行时映像。 运行时需要可用的设置(例如端口和环境变量)都在此处。 在快速模式下从 VS 运行时使用此阶段(调试配置的默认值)。
build
该项目在此阶段生成。 使用 .NET SDK 基础映像,该映像具有生成项目所需的组件。
发布...
此阶段派生自生成阶段并发布项目,该项目将复制到最终阶段。
final
此阶段配置了如何启动应用,并在生产环境中或在常规模式下从 VS 运行时使用(不使用调试配置时的默认值)。
aotdebug
从 VS 启动时,此阶段用作最终阶段的基础,以支持在常规模式下进行调试(不使用调试配置时的默认值)。
备注
仅 Linux 容器支持该 aotdebug 阶段。 如果在项目上启用了 本机预先 (AOT) 部署,则会在 Visual Studio 2022 17.11 及更高版本中使用它。