本章我们要实现的是通过我们往代码仓库push代码后,我们将每次的push进行一次docker自动化打包发布到docker hub中,发布到之后我将进行部署环节,我们将通过ssh方式将我们的.NET应用程序pull并run到我们的云服务器上。
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 ["WebApplication1/WebApplication1.csproj", "WebApplication1/"] RUN dotnet restore "WebApplication1/WebApplication1.csproj" COPY . . WORKDIR "/src/WebApplication1" RUN dotnet build "WebApplication1.csproj" -c Release -o /app/build FROM build AS publish RUN dotnet publish "WebApplication1.csproj" -c Release -o /app/publish FROM base AS final WORKDIR /app COPY --from=publish /app/publish . ENTRYPOINT ["dotnet", "WebApplication1.dll"] pipeline配置这个环节我们将推送docker镜像到dockerhub中,关于pipeline的配置可以参考一下前两章对于dockerhub推送都有介绍
# ASP.NET Core # Build and test ASP.NET Core projects targeting .NET Core. # Add steps that run tests, create a NuGet package, deploy, and more: # https://docs.microsoft.com/azure/devops/pipelines/languages/dotnet-core trigger: - demo04 pool: vmImage: 'ubuntu-latest' variables: buildConfiguration: 'Release' steps: - task: UseDotNet@2 inputs: packageType: 'sdk' version: '3.x' - task: DotNetCoreCLI@2 inputs: command: 'restore' feedsToUse: 'select' - task: DotNetCoreCLI@2 inputs: command: 'build' - task: DotNetCoreCLI@2 inputs: command: 'publish' publishWebProjects: true - task: Docker@2 inputs: containerRegistry: 'DockerHub' repository: '$(repository)' command: 'buildAndPush' Dockerfile: 'WebApplication1/Dockerfile' buildContext: '.' tags: 'latest' 在云服务上自动部署应用程序第一步我们需要先去service connection中区创建一个ssh的连接信息,以用于后续的操作。
接下来我们需要创建一个 release pipeline 用于我们部署的操作,如下图所示:
下图的四个task向我们展示了部署阶段的操作步骤.
删除容器
我们先去看我们服务器当中的容器是否存在,如果该容器不存在则我们跳出该操作,如果存在我们则去删除指定的容器.
#判断是否存在containername容器 docker ps | grep containername&> /dev/null #如果存在,则Remove if [ $? -ne 0 ] then echo "containername container not exist continue.. " else echo "remove containername container" docker rm containername -f fi删除镜像
查看服务器指定的镜像是否存在,如果不存在则跳出该操作,否则我们将删除指定的镜像
#判断是否存在name镜像 docker images | grep name&> /dev/null #如果不存在,则跳出 if [ $? -ne 0 ] then echo "image does not exist , continue..." else echo "image exists !!! remove it" docker rmi --force name fi拉取镜像
拉取指定的镜像到服务器
docker pull hueifeng/test:latest运行镜像
运行拉取的镜像hueifeng/test,并将其命名为name,对外开放端口8108端口.