visual-studio - 在单独的层中复制多个项目文件还是在创建Docker镜像时一次性复制多个项目文件更好?

标签 visual-studio docker dockerfile docker-copy

我正在从此.NET Core应用程序中创建一个Docker容器,该容器在解决方案内部具有多个项目,我想知道单独或在一行中对每个项目文件进行COPY更好吗?

Visual Studio生成一个Dockerfile,将每个项目文件复制到新行中,如下所示:

WORKDIR /src
COPY Dir1/Dir1.csproj Dir1/
COPY Dir2/Dir2.csproj Dir2/
COPY Dir3/Dir4/Dir4.csproj Dir3/Dir4/
RUN dotnet restore Dir1/Dir1.csproj

但是,用于使用Docker创建.NET应用程序的Microsoft documentation显示为“优化”,使其仅使用单个COPY语句,如下所示:
WORKDIR /src
COPY . .
RUN dotnet restore Dir1/Dir1.csproj

在我对本文的理解中,据说可以创建更大的图像,但是如果一个项目发生更改,则不必对所有其他项目进行COPY

有趣的是,Docker documentation提到

COPY them individually, rather than all at once. This ensures that each step’s build cache is only invalidated (forcing the step to be re-run) if the specifically required files change.



基本上与Microsoft文章所说的有关,当一个项目更改时必须重新运行COPY步骤。

我想知道哪种选择更好,为什么,或者出于什么目的。或者,也许我误解了一些文档,然后请向我解释其中的区别。

最佳答案

IMO的最佳实践方法是将每个项目复制为一个单独的层,即专用的COPY语句。

使用分开的层。

  • 建立速度更快:
    docker正在缓存图层,因此,如果您在一个项目中进行了更改-
    下次构建镜像时,docker将仅构建更改的层
    并为其他使用缓存。
  • 部署速度更快:层可以并行拉动
  • 高效托管:借助docker copy on write机制,可以在图像之间共享层以节省空间和IO:

  • Copy-on-write is a strategy of sharing and copying files for maximum efficiency. If a file or directory exists in a lower layer within the image, and another layer (including the writable layer) needs read access to it, it just uses the existing file. The first time another layer needs to modify the file (when building the image or running the container), the file is copied into that layer and modified. This minimizes I/O and the size of each of the subsequent layers



    之所以在Dockerfiles中看到常见的COPY . .语句,是因为通常dockerfile包含一个项目,这也是我也要针对您的情况推荐的最佳实践-在每个项目中放置一个dockerfile并构建单独的镜像(常见的基本图片)。

    如果您应该将所有项目托管在一个镜像中,请至少将它们复制为不同的层。

    关于visual-studio - 在单独的层中复制多个项目文件还是在创建Docker镜像时一次性复制多个项目文件更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57148332/

    相关文章:

    C# 如何从 .t​​xt 文件中的列表中读取并将它们放入列表中?

    docker - 在 Docker 中以 headful 模式执行 puppeteer 的问题

    nginx - 错误 28105#0 : *1 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream

    build - 使用apt-get构建部门最小化Docker镜像

    mysql - 无法在 Docker-Compose 文件中将本地数据库映射到(mysql 镜像中的卷)

    c - Visual Studio 中是否有等效的语句表达式?

    c# - 如何通过 DllImport 将 double 组从 C# 传递到 C++

    visual-studio - Qt5、Visual Studio 2012 Express 和 OpenMp。如何?

    docker - 如何将CouchDB服务器添加到Docker创建文件中

    Docker-compose:在 env 文件中设置一个变量并在 Dockerfile 中使用它