C# .NET 5.0 部署到Docker


C# .NET 5.0 部署到Docker

VS中存在Docker部署工具

1.创建项目时,勾选Docker支持,如果没有选择,创建项目后也可支持,如下所示

2.选择项目==》右键添加==》Docker支持

 自动新增Dockerfile文件

 同时,launchSettings.json 文件新增Docker,可在Docker中调试

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:48098",
      "sslPort": 44372
    }
  },
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "Asp.Netcore.Demos": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "dotnetRunMessages": "true",
      "applicationUrl": "https://localhost:5001;http://localhost:5000"
    },
    "Docker": {
      "commandName": "Docker",
      "launchBrowser": true,
      "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger",
      "publishAllPorts": true,
      "useSSL": true
    }
  }
}

Dockerfile文件解释:

#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

#--------------------多阶段构建 4个阶段,提升效率-----------------------------
#基础阶段
FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
#构建阶段,包含所有构建工具
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /src
COPY ["Asp.Netcore.Demos.csproj", "."]
COPY ["../Models/Models.csproj", "../Models/"]
RUN dotnet restore "./Asp.Netcore.Demos.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "Asp.Netcore.Demos.csproj" -c Release -o /app/build
#发布阶段
FROM build AS publish
RUN dotnet publish "Asp.Netcore.Demos.csproj" -c Release -o /app/publish
#最终阶段
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Asp.Netcore.Demos.dll"]

 有了Dockerfile就可以创建镜像:

注:需要下载并安装 Docker Desktop应用,略

安装过程遇到问题:

发生原因(参考:https://blog.csdn.net/u013374164/article/details/115841910):

如果下载的是官网中最新的版本的docker的话,会出现该问题,原因是最新版本docker需要安装在window10系统环境下。

如果是win7安装的话,可使用:http://mirrors.aliyun.com/docker-toolbox/windows/docker-toolbox/ 进行安装,亲测有效
————————————————

 选择Dockerfile文件==》右键==》生成Docker映像,如下所示:

1.查看docker images 镜像

cmd==》docker images

相关