Jenkins部署 .NetCore到服务器

1. .NetCore项目支持windows 服务

参考:https://docs.microsoft.com/zh-cn/aspnet/core/host-and-deploy/windows-service?view=aspnetcore-3.1&tabs=visual-studio

添加Nuget包:Microsoft.Extensions.Hosting.WindowsServices

.NetCore 3.1 program.cs无需修改,2.X:

            //CreateHostBuilder(args).Build().Run(); //3.1 默认写法

            //判断 是否是服务方式
            var isService = !(Debugger.IsAttached || args.Contains("--console"));

            var builder = CreateHostBuilder(
                args.Where(arg => arg != "--console").ToArray());

            if (isService)
            {
                var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
                var pathToContentRoot = Path.GetDirectoryName(pathToExe);
                Directory.SetCurrentDirectory(pathToContentRoot);

                // To run the app without the CustomWebHostService change the
                // next line to host.RunAsService();
                //builder.UseWindowsService();//使用服务方式 3.x

                host.RunAsCustomService();//2.x

            }

            builder.Build().Run();//启动

 

2. power shell 脚本

Stop.ps1:

$ArrService = @("ConsulApiTestA","ConsulApiTestB")#服务名称
foreach ($srvName in $ArrService)
{
    #获取进程
    #$prc = Get-Process -Name $srvName -ErrorAction SilentlyContinue 
    #if (-not($prc -eq $null))
    #{
    #    Write-Host "Stopping " $prc.ProcessName
    #    Stop-Process -InputObject $prc -ErrorAction SilentlyContinue -Force
    #}
    $srv = Get-Service -Name $srvName -ErrorAction SilentlyContinue 
    if(-not($srv -eq $null)){
        write-host $srv.displayname "("$srv.status")" -foregroundcolor "green"
        if($srv.status -eq "running"){ #running状态
            Stop-Service -Name $srvName #停止服务
        }
        sc.exe delete $srvName
    }
}
exit

Start.ps1:

New-Service -Name ConsulApiTestA -BinaryPathName D:\WebDemo\ConsulApiTest\ConsulApiTestA\ConsulApiTestA.exe -Description "ConsulApiTestA 测试Jenkins 部署.Net Core 项目" -DisplayName "ConsulApiTestA-Test" -StartupType Automatic
Start-Sleep –s 1
Start-Service -Name ConsulApiTestA

New-Service -Name ConsulApiTestB -BinaryPathName D:\WebDemo\ConsulApiTest\ConsulApiTestB\ConsulApiTestB.exe -Description "ConsulApiTestB 测试Jenkins 部署.Net Core 项目" -DisplayName "ConsulApiTestB-Test" -StartupType Automatic
Start-Sleep –s 1
Start-Service -Name ConsulApiTestB

exit

3.jenkins配置

ssh发送编译后文件前,先停止服务并删除

 编译项目

ssh发送文件&创建启动服务

 

注:ssh 直接bat执行 exe或 dotnet *.dll 再ssh连接结束后,.netCore服务程序会被强制停止.

linux 解决办法 nohup,windows解决办法 cygwin终端模拟linux命令

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章