.Net Core项目使用Docker容器部署到Linux服务器Centos7

 2020-2-11      DotNet  Docker  Centos  Linux 

必备环境:Docker
Docker 安装文档 : http://blog.raikay.com/post/2020/docker/

创建项目

选择 ASP.NET Core Web 应用程序

IMG

可以在创建时直接勾选【启用Docker支持】选择Linux(图1),也可以在已有项目右键添加Docker支持(图2)

图1

IMG

图2

IMG

项目发送至Linux服务器,我这里是上传到github,然后在linux服务器通过github下载项目

IMG

git下载项目

git clone https://github.com/raikay/firstdemo.git

构建镜像

 docker build -t firstdemo . -f firstdemo/Dockerfile

IMG

如果构建dotnet环境太慢,可以使用腾讯加速镜像下载

docker pull ccr.ccs.tencentyun.com/dotnet-core/aspnet:3.1-buster-slim

docker tag ccr.ccs.tencentyun.com/dotnet-core/aspnet:3.1-buster-slim mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim
docker pull ccr.ccs.tencentyun.com/dotnet-core/sdk:3.1-buster

docker tag ccr.ccs.tencentyun.com/dotnet-core/sdk:3.1-buster mcr.microsoft.com/dotnet/core/sdk:3.1-buster
docker build -t firstdemo . -f firstdemo/Dockerfile

运行镜像

docker run -d -p 1080:80 --name myfirstdemo  firstdemo

浏览器访问

http://192.168.198.131:1080/WeatherForecast

IMG

浏览器显示效果

IMG

Dockerfile解释

#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.
#引入aspnet:3.1-buster-slim镜像并重命名为 base
FROM http://mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
#设置base镜像的工作目录为/app
WORKDIR /app
#开放容器的80与443端口
EXPOSE 80
EXPOSE 443

#引入sdk:3.1-buster镜像并重命名为build
#该镜像用于在Linux平台上生成我们的项目并不包含在最终镜像中
FROM http://mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
#设置build镜像的工作目录为/src
WORKDIR /src
#拷贝项目文件DemoWeb.csproj到/src/DemoWeb/目录
COPY ["DemoWeb/DemoWeb.csproj", "DemoWeb/"]
#运行dotnet restore命令还原项目的依赖
RUN dotnet restore "DemoWeb/DemoWeb.csproj"
#拷贝Dockerfile所在目录的内容到/src目录
COPY . .
#设置工作目录为build镜像的/src/DemoWeb
WORKDIR "/src/DemoWeb"
#运行 dotnet build 生成命令,并将输出内容保存到/app/build目录
RUN dotnet build "DemoWeb.csproj" -c Release -o /app/build

FROM build AS publish
#运行 dotnet publish 发布命令,并将输入内容保存到/app/publish目录
RUN dotnet publish "DemoWeb.csproj" -c Release -o /app/publish

#使用base镜像最为最终的基础镜像
FROM base AS final
WORKDIR /app
#将publish镜像中/app/publish目录的内容拷贝到当前的/app目录
COPY --from=publish /app/publish .
#设置该镜像的入口命令为 dotnet DemoWeb.dll
ENTRYPOINT ["dotnet", "DemoWeb.dll"]