目標:
建構一個 .Net Core console 專案,並且建構一個 類別庫 (.NET Standard) 供其引用環境:
Net Core 2.0.3Docker version 17.11.0-ce, build 1caf76c
## Net Core Console 專案引用 .NET Standard 範例
// 建立 console 專案
dotnet new console -lang c# --name myApp
// 建立 .Net Standard Library
dotnet new classlib -lang c# --name myLibrary
// myLibrary/Class1.cs 修改內容如下
using System; namespace myLibrary public class Class1 { static public void TestRun() { Console.WriteLine("Run {0}.{1}." , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName , System.Reflection.MethodBase.GetCurrentMethod().Name); } } }
// myApp 加入並引用參考 myLibrary.csproj
cd myApp
dotnet add reference ..\myLibrary\myLibrary.csproj
// myApp/Program.cs 修改內容如下
using System; namespace myApp { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); myLibrary.Class1.TestRun(); Console.ReadLine(); } } }
// 試運行
dotnet restore
dotnet run
// 運行結果如下
PS D:\NetCoreDockerImage2Example\myApp>dotnet run
Hello World!
Run myLibrary.Class1.TestRun.
建立 Docker Image
建立 Dockerfile
在主資料夾內建立一個 Dockerfile 檔案, 內容如下# copy csproj and restore as distinct layers COPY myApp/*.csproj ./myApp/ COPY myLibrary/*.csproj ./myLibrary/ WORKDIR /app/myApp RUN dotnet restore # copy everything else and build WORKDIR /app COPY myApp/ ./myApp/ COPY myLibrary/ ./myLibrary/ WORKDIR /app/myApp RUN dotnet publish -c Release -o out # build runtime image FROM microsoft/dotnet:runtime WORKDIR /app/myApp COPY --from=build-env /app/myApp/out ./ ENTRYPOINT ["dotnet", "myApp.dll"]### 其中最後一行中的 "myApp.dll" 要修改對應到你專案產生的dll名稱
執行編譯 Docker Image
docker build -t dotnetmyapp2 .
執行成功會有以下訊息 (20ae9d152e3d 這個每次編譯都不一樣得值)
Successfully built 20ae9d152e3d
Successfully tagged dotnetmyapp2:latest
執行 docker
docker run --name testdotnetmyapp dotnetmyapp2
可以看到執行回應
Hello World!
Run myLibrary.Class1.TestRun.