How to include dependencies in .NET Core app docke

2019-04-20 10:44发布

问题:

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.

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}");
        }
    }
}

It just has one NuGet dependency on Newtonsoft.Json. When I run the app from Visual Studio, everything works fine.

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'

This is to be expected because Newtonsoft.Json.dll is not being copied by Visual Studio to the output folder.

Here's the Dockerfile I'm using:

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

Is there a recommended way of dealing with this problem?

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).

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.

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).

回答1:

After some more reading I finally figured it out.

Instead of dotnet build you run:

dotnet publish

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.



回答2:

I wrote a tutorial on this recently. The Dockerfile contents I used were (slightly modified to remove the ASP.NET Core bits):

FROM microsoft/dotnet:latest
COPY . /app
WORKDIR /app

RUN ["dotnet", "restore"]
RUN ["dotnet", "build"]

ENTRYPOINT ["dotnet", "run"]

When you run docker build, it uses the Dockerfile as a "recipe" to build the image. It'll run dotnet restore and dotnet build first, then package everything up into the image. The resulting image has everything the app needs to run on any Docker host.