【问题标题】:How to include dependencies in .NET Core app docker image?如何在 .NET Core 应用程序 docker 映像中包含依赖项?
【发布时间】:2016-12-12 07:04:07
【问题描述】:

我正在尝试构建一个 .NET Core 应用程序 docker 映像。但我不知道应该如何将项目的 NuGet 依赖项放入映像中。

为简单起见,我创建了一个 .NET Core 控制台应用程序:

using System;
using Newtonsoft.Json;

namespace ConsoleCoreTestApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine($"Hello World: {JsonConvert.False}");
        }
    }
}

它只有一个 NuGet 依赖于 Newtonsoft.Json。当我从 Visual Studio 运行应用程序时,一切正常。

但是,当我从项目创建 Docker 映像并尝试从那里执行应用程序时,它找不到依赖项:

# dotnet ConsoleCoreTestApp.dll
Error: assembly specified in the dependencies manifest was not found -- package: 'Newtonsoft.Json', version: '9.0.1', path: 'lib/netstandard1.0/Newtonsoft.Json.dll'

这是意料之中的,因为 Newtonsoft.Json.dll 没有被 Visual Studio 复制到输出文件夹。

这是我正在使用的Dockerfile:

FROM microsoft/dotnet:1.0.0-core
COPY bin/Debug /app

有没有推荐的方法来处理这个问题?

我不想在容器内运行dotnet restore(因为我不想在每次容器运行时都重新下载所有依赖项)。

我想我可以在Dockerfile 中添加一个RUN dotnet restore 条目,但是我不能再将microsoft/dotnet:<version>-core 用作基本映像。

而且我找不到让 Visual Studio 将所有依赖项复制到输出文件夹中的方法(就像对常规 .NET Framework 项目所做的那样)。

【问题讨论】:

  • 我不是 .net 人,所以请原谅我的无知...为什么添加 RUN dotnet restore 会阻止您使用 dotnet 基础映像?
  • @Matt 是正确的,它不应该阻止您使用 microsoft/dotnet 基本图像。
  • @Matt 因为核心映像不包含恢复命令。
  • @SebastianKrysmanski oic .. 所以就像 jre 而不是 jdk。缺少一些开发位。
  • @Matt 是的,就是这样。核心映像只是运行时。

标签: c# visual-studio docker .net-core


【解决方案1】:

看了几遍,终于明白了。

你运行的是dotnet build:

dotnet publish

这会将所有文件(包括依赖项)放在publish 文件夹中。然后这个文件夹可以直接与microsoft/dotnet:<version>-core 图像一起使用。

【讨论】:

    【解决方案2】:

    我最近为此写了tutorial。我使用的 Dockerfile 内容是(稍作修改以删除 ASP.NET Core 位):

    FROM microsoft/dotnet:latest
    COPY . /app
    WORKDIR /app
    
    RUN ["dotnet", "restore"]
    RUN ["dotnet", "build"]
    
    ENTRYPOINT ["dotnet", "run"]
    

    当您运行 docker build 时,它使用 Dockerfile 作为“配方”来构建映像。它将首先运行dotnet restore 和dotnet build,然后 将所有内容打包到图像中。生成的映像包含应用程序在任何 Docker 主机上运行所需的一切。

    【讨论】:

    • 不幸的是,这不适用于dotnet:xxx-core 图像。不过,我不确定dotnet 和dotnet:xxx-core 作为基本图像之间的区别是否相关。
    • @SebastianKrysmanski 只是好奇,你为什么要使用dotnet:xxx-core 而不是dotnet:latest?
    • 无特殊原因。对我来说,这似乎是最合乎逻辑/最小的解决方案。另外,我尽量不将源代码放入容器中。
    猜你喜欢
    • 2020-07-08
    • 1970-01-01
    • 2018-01-23
    • 2021-06-12
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 2021-03-22
    • 2010-09-11
    相关资源
    最近更新 更多