gpt4 book ai didi

asp.net-core - 如何在 Dockerfile 中正确使用 dotnet Restore

转载 作者:行者123 更新时间:2023-12-02 14:36:34 29 4
gpt4 key购买 nike

向 ASP.NET Core 项目添加 docker 支持时,VS (15.9.2) 将添加一个默认的 Dockerfile,用于恢复、构建和发布。但是,它不是将所有文件复制到 Docker 构建容器中,而是首先仅复制 proj 文件,进行恢复,然后在构建之前复制其余文件。我想知道为什么要这样做?这与直接复制所有文件然后进行恢复有何不同?

这种方法的问题在于,解决方案中的所有 proj 文件都需要单独复制,如果项目真的很大,并且不时添加和删除项目,那么保持 Dockerfile 同步有点困难有了这个。我只是想知道为什么这样做,以及复制所有内容是否也可以?

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

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

最佳答案

当 Docker 构建镜像时,它会维护一个 build cache :

When building an image, Docker steps through the instructions in your Dockerfile, executing each in the order specified. As each instruction is examined, Docker looks for an existing image in its cache that it can reuse, rather than creating a new (duplicate) image.

重要的是,ADDCOPY 指令得到特殊处理:

For the ADD and COPY instructions, the contents of the file(s) in the image are examined and a checksum is calculated for each file. The last-modified and last-accessed times of the file(s) are not considered in these checksums. During the cache lookup, the checksum is compared against the checksum in the existing images. If anything has changed in the file(s), such as the contents and metadata, then the cache is invalidated.

在构建 .NET Core 解决方案时,我们可以确定,在运行 dotnet Restore 后,再次运行 dotnet Restore 的结果只会在以下情况下发生变化: .csproj 文件已更改(例如,添加了新包或更改了版本)。

通过将.csproj文件单独复制到镜像中,我们可以利用Docker的构建缓存,这意味着只要.csproj 文件没有更改,每次重建镜像时都不会不必要地重新执行 dotnet Restore 步骤。

关于asp.net-core - 如何在 Dockerfile 中正确使用 dotnet Restore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53460002/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com