vlambda博客
学习文章列表

已发布好的.NET Core项目文件如何打包为Docker镜像文件

问题描述

在博文(【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"]

已发布好的.NET Core项目文件如何打包为Docker镜像文件

  • 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/)

 已发布好的.NET Core项目文件如何打包为Docker镜像文件

当命令运行完成后,在Docker Desktop页面中可以看见当前Images

已发布好的.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结果为:

 

 参考资料:

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

出处:https://www.cnblogs.com/lulight/p/14318686.html