3

Linux系统使用Docker部署ASP.NET Core应用程序

 2 years ago
source link: http://ocdman.github.io/2020/07/24/Linux%E7%B3%BB%E7%BB%9F%E4%BD%BF%E7%94%A8Docker%E9%83%A8%E7%BD%B2ASP-NET-Core%E5%BA%94%E7%94%A8%E7%A8%8B%E5%BA%8F/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

好久没有写关于配置的文章了,今天来说一下怎么在Linux系统下使用Docker部署ASP.NET Core的应用程序。

首先Linux使用的版本为Ubuntu,并且要安装好Docker。开发工具使用的是Visual Studio 2019。应用程序的.NET Core版本为ASP.NET Core 3.1。

编写Dockerfile

Docker中的最小单位为容器,而Dockerfile是定义单个容器的内容和启动行为的文本文件。假设应用程序名称为WebApplication2,以下是开发工具自动生成的Dockerfile

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

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
WORKDIR /src
COPY ["WebApplication2/WebApplication2.csproj", "WebApplication2/"]
RUN dotnet restore "WebApplication2/WebApplication2.csproj"
COPY . .
WORKDIR "/src/WebApplication2"
RUN dotnet build "WebApplication2.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "WebApplication2.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "WebApplication2.dll"]

里面有一些build、publish、restore命令,帮助我们快速使用命令行来执行生成、发布、还原等操作。这里我们不用自动生成的Dockerfile,使用自己的Dockerfile

# 使用运行时镜像
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim
# 设置工作目录
WORKDIR /app
# 把目录下的内容都复制到当前目录下
COPY . .
# 暴露80端口
EXPOSE 80
# 运行镜像入口命令和可执行文件名称
ENTRYPOINT ["dotnet", "WebApplication2.dll"]

然后修改Dockerfile的文件属性,复制到输出目录一栏选择始终复制。保证Dockerfile文件可以随程序一起发布。

生成Docker镜像

使用POWERSHELL自带的scp命令将开发工具发布的publish文件夹上传到Linux服务器,然后使用ssh进入服务器下的该目录。publish文件夹中的内容主要包括以下内容,

publish

​ |- Dockerfile

​ |- web.config

​ |- appsettings.json

​ |- WebApplication2.dll

​ | - WebApplication2.exe

​ |- WebApplication2.deps.json

​ |- WebApplication2.runtimeconfig.json

使用下面的命令生成Docker镜像,注意全部小写

docker build -t webapplication2 .

docker build命令会根据Dockerfile中的配置,依次执行每一条命令。第一次执行FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim命令的时候,会检查docker镜像中是否已存在名为mcr.microsoft.com/dotnet/core/aspnet,Tag为3.1-buster-slim的镜像,如果没有则自动下载该镜像。

等待下载完毕后,如果生成Docker镜像成功的话,可以执行命令来查看镜像

docker images

运行Docker镜像

Docker镜像生成之后,接下来就是运行容器镜像了。执行以下命令

docker run --name=webapplication2 -p 5000:80 -d webapplication2

以下是一些可选参数,及其说明

  • --name:指定容器的别名
  • -p:将Linux服务器上的5000端口映射到容器中的默认80端口,端口映射关系host:container
  • -d:将容器以后台进程的方式启动
  • -it:将容器以交互模式运行容器,方便调试以及查看输出
  • --rm:在容器退出后自动删除当前容器,开发模式下的常用参数
  • --restart:指定容器非正常退出时的重启策略,如果设置为--restart=always,表示非正常退出的情况下,始终重新启动容器
  • webapplication2:要启动的本地镜像名称

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK