【Azure Developer】已釋出好的.NET Core專案檔案如何打包為Docker映象檔案

路邊兩盞燈 發表於 2021-01-23

問題描述

在博文(【Azure App Service For Container】建立ASP.NET Core Blazor專案並打包為Linux映象釋出到Azure應用服務)中我們通過VS 2019可以為專案新增Dockerfile並自動生成Docker Image檔案。但是如果不借助於VS2019我們如何來操作呢?

 

解決步驟

準備Dockerfile

進入專案資料夾中,建立Dockerfile並COPY以下內容:

#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

#Depending on the operating system of the host machines(s) that will build or run the containers, the image specified in the FROM statement may need to be changed.
#For more information, please see https://aka.ms/containercompat

FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
ENV ASPNETCORE_URLS=http://+:8000 
WORKDIR /app EXPOSE 8000 EXPOSE 5000 COPY . /app/ ENTRYPOINT ["dotnet", "MyLife.Blazor.Server.dll"]
  • FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base  和 FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build 可以在Docker Hub中查詢到對於的版本映象(https://hub.docker.com/_/microsoft-dotnet-sdk)
  • COPY . /app/ 即把dockerfile所在的目錄中所有檔案複製到映象中app目錄中

 

生成映象

通過CMD進入到當前目錄, 使用 docker build -t mywebimages (特別注意:在命令中必須要點.,黃色高亮的部分替代為自定義的映象名。詳細的命令參考Docker說明:https://docs.docker.com/engine/reference/commandline/build/

 【Azure Developer】已釋出好的.NET Core專案檔案如何打包為Docker映象檔案

當命令執行完成後,在Docker Desktop頁面中可以看見當前Images

【Azure Developer】已釋出好的.NET Core專案檔案如何打包為Docker映象檔案

 

執行映象,驗證專案執行成功

在Docker Desktop中Run當前Image或者通過docker run命令啟動Container: docker run --name testweb -p 8080:8000 mywebimages

 命令啟動輸出:

C:\MyCode\MyLife\MyLife.Blazor\MyLife.Blazor\Server\bin\Release\net5.0\publish>docker run --name testapidemo -p 8080:8000 mywebimages
warn: Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository[60]
Storing keys in a directory 'C:\Users\ContainerUser\AppData\Local\ASP.NET\DataProtection-Keys' that may not be persisted outside of the container. Protected data will be unavailable when container is destroyed.
info: Microsoft.Hosting.Lifetime[0]
Now listening on: http://[::]:8000
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
Content root path: C:\app
warn: Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3]
Failed to determine the https port for redirect.

 

 

訪問Docker Container指定的埠8080結果為:

【Azure Developer】已釋出好的.NET Core專案檔案如何打包為Docker映象檔案

 

 參考資料:

Docker Hub: https://hub.docker.com/_/microsoft-dotnet-sdk

建立ASP.NET Core Blazor專案並打包為Linux映象釋出到Azure應用服務: https://www.cnblogs.com/lulight/p/14315383.html

windows上用VS2019開發的 .NETCore專案如何打包部署到linux Docker中: https://blog.csdn.net/weixin_48000648/article/details/106524426