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命令

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