如何在 .NET Core 应用程序 docker 映像中包含依赖项? [英] How to include dependencies in .NET Core app docker image?
问题描述
我正在尝试构建 .NET Core 应用 docker 映像.但我不知道我应该如何将项目的 NuGet 依赖项放入映像中.
I'm trying to build a .NET Core app docker image. But I can't figure out how I'm supposed to get the project's NuGet dependencies into the image.
为了简单起见,我创建了一个 .NET Core 控制台应用程序:
For simplicity reasons I've create a .NET Core console application:
using System;
using Newtonsoft.Json;
namespace ConsoleCoreTestApp
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine($"Hello World: {JsonConvert.False}");
}
}
}
它只对 Newtonsoft.Json
有一个 NuGet 依赖.当我从 Visual Studio 运行应用程序时,一切正常.
It just has one NuGet dependency on Newtonsoft.Json
. When I run the app from Visual Studio, everything works fine.
但是,当我从项目创建 Docker 映像并尝试从那里执行应用程序时,它找不到依赖项:
However, when I create a Docker image from the project and try to execute the app from there, it can't find the dependency:
# 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 复制到输出文件夹.
This is to be expected because Newtonsoft.Json.dll
is not being copied by Visual Studio to the output folder.
这是我正在使用的 Dockerfile
:
FROM microsoft/dotnet:1.0.0-core
COPY bin/Debug /app
有没有推荐的方法来处理这个问题?
Is there a recommended way of dealing with this problem?
我不想在容器内运行 dotnet restore
(因为我不想在每次容器运行时重新下载所有依赖项).
I don't want to run dotnet restore
inside of the container (as I don't want to re-download all dependencies everytime the container runs).
我想我可以在 Dockerfile
中添加一个 RUN dotnet restore
条目,但后来我无法使用 microsoft/dotnet:<version>-core
不再作为基本图像.
I guess I could add a RUN dotnet restore
entry to the Dockerfile
but then I couldn't use microsoft/dotnet:<version>-core
as base image anymore.
而且我找不到让 Visual Studio 将所有依赖项复制到输出文件夹中的方法(就像它对常规 .NET Framework 项目所做的那样).
And I couldn't find a way to make Visual Studio copy all dependencies into the output folder (like it does with regular .NET Framework projects).
推荐答案
经过一些阅读,我终于明白了.
After some more reading I finally figured it out.
你运行的不是 dotnet build
:
dotnet publish
这会将所有文件(包括依赖项)放在 publish
文件夹中.然后该文件夹可以直接与 microsoft/dotnet:<version>-core
图像一起使用.
This will place all files (including dependencies) in a publish
folder. And this folder then can be used directly with a microsoft/dotnet:<version>-core
image.
这篇关于如何在 .NET Core 应用程序 docker 映像中包含依赖项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!