使用 Docker Buildkit --mount=type=cache 缓存 .NET 5 dockerfile 的 Nuget 包

SKK*_*SKK 9 docker .net-core dockerfile asp.net5

目前我正在为 vue+mvc .net 5 混合应用程序创建一个 dockerfile。为此,我需要安装 nodeJS、nuget 包以及 webpack。每次我尝试构建图像时,大约需要 30 分钟。我探索了如何减少构建时间,然后我了解了提供缓存挂载的新 Docker Buildkit 功能。但是,我没有找到太多专门使用 nuget 包的示例或文档。

请有人帮助我提供任何已为 nuget 包实现 --mount=type=cache 的示例 dockerfile。

rob*_*b3c 13

关键是在需要访问相同包缓存的--mount=type=cache所有 dockerfile 命令中使用相同的参数(例如,,,)。RUNdocker restoredocker builddocker publish

这是一个简短的 dockerfile 示例,显示了相同的内容,并且在不同的调用中--mount=type=cache具有相同的id分布dotnet restore/build/publish。默认情况下,分离调用并不总是必要的,并且build会同时执行这两种操作,但这种方式显示了在多个命令之间共享相同的缓存。缓存挂载声明仅出现在 dockerfile 本身中,不需要.restorepublishdocker build

该示例还展示了如何使用 BuildKit--mount=type=secret参数传入NuGet.Config文件,该文件可配置为访问私有 nuget feed 等。默认情况下,以这种方式传递的秘密文件出现在 中,但您可以通过命令中的属性/run/secrets/<secret-id>更改它们的位置。它们仅在调用期间存在,不会保留在最终图像中。targetdocker buildRUN

# syntax=docker/dockerfile:1.2
FROM my-dotnet-sdk-image as builder
WORKDIR "/src"
COPY "path/to/project/src" .

RUN --mount=type=cache,id=nuget,target=/root/.nuget/packages \
    --mount=type=secret,id=nugetconfig \
    dotnet restore "MyProject.csproj" \
    --configfile /run/secrets/nugetconfig \
    --runtime linux-x64

RUN --mount=type=cache,id=nuget,target=/root/.nuget/packages \
    dotnet build "MyProject.csproj" \
    --no-restore \
    --configuration Release \
    --framework netcoreapp3.1 \
    --runtime linux-x64

RUN --mount=type=cache,id=nuget,target=/root/.nuget/packages \
    dotnet publish "MyProject.csproj" \
    --no-restore \
    --no-build \
    -p:PublishReadyToRun=true \
    -p:PublishReadyToRunShowWarnings=true \
    -p:TieredCompilation=false \
    -p:TieredCompilationQuickJit=false \
    --configuration Release \
    --framework netcoreapp3.1 \
    --runtime linux-x64
Run Code Online (Sandbox Code Playgroud)

docker build传入nugetconfig私有源文件的示例命令可能是:

docker build --secret id=nugetconfig,src=path/to/nuget.config -t my-dotnet-image .

DOCKER_BUILDKIT=1对于该命令,需要设置环境变量。

或者,您可以使用buildx

docker buildx build --secret id=nugetconfig,src=path/to/nuget.config -t my-dotnet-image .

  • @MuhammadRehanSaeed 我目前正在使用 Linux 容器的 Windows 主机上工作。该“目标”值是将缓存安装在容器内的位置。Docker 本身管理它在主机上本地存储的位置,而我们无法直接访问它。 (2认同)