关键是在所有需要访问相同包缓存的 dockerfile RUN 命令中使用相同的 --mount=type=cache 参数(例如,docker restore、docker build、docker publish)。
这是一个简短的 dockerfile 示例,显示相同的 --mount=type=cache 和相同的 id 分布在不同的 dotnet restore/build/publish 调用中。分离调用并不总是必要的,因为默认情况下build 将restore 和publish 两者都做,但这种方式显示在多个命令之间共享相同的缓存。缓存挂载声明仅出现在 dockerfile 本身中,不需要 docker build 中的参数。
该示例还显示了如何使用 BuildKit --mount=type=secret 参数传入一个 NuGet.Config 文件,该文件可以配置为访问例如私人 nuget 提要。默认情况下,以这种方式传递的秘密文件出现在/run/secrets/<secret-id> 中,但您可以通过docker build 命令中的target 属性更改它们的去向。它们仅在 RUN 调用期间存在,不会保留在最终图像中。
# 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
在nugetconfig 文件中传递私有供稿的示例docker build 命令可能是:
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 .