一.相關介紹 Dockerfile:關於Dockerfile的使用說明,我在文章《讓.NetCore程式跑在任何有docker的地方》中有說到,這裡不在贅述,需要的可以先看下,本文主要介紹Jenkinsfile結合dockerfile配合使用,自動構建.NetCore應用程式。 Jenkinsfil ...
一.相關介紹
Dockerfile:關於Dockerfile的使用說明,我在文章《讓.NetCore程式跑在任何有docker的地方》中有說到,這裡不在贅述,需要的可以先看下,本文主要介紹Jenkinsfile結合dockerfile配合使用,自動構建.NetCore應用程式。 Jenkinsfile :Jenkinsfile 是 Jenkins 2.x 或更高版本核心特性 Pipeline(流水線) 的腳本,或者說對於Jenkins 流水線的定義被寫在一個叫Jenkinsfile的文本文件中,該文件可以被提交到項目的源代碼的控制倉庫。這是"流水線即代碼"的基礎; 將CD 流水線作為應用程式的一部分,像其他代碼一樣進行版本化和審查。 創建 `Jenkinsfile`並提交它到源代碼控制中提供了以下幾個好處:- 自動地為所有分支創建流水線構建過程並拉取請求。
- 在流水線上代碼複查/迭代 (以及剩餘的源代碼)。
- 對流水線進行審計跟蹤。
- 該流水線的真正的源代碼 , 可以被項目的多個成員查看和編輯。
二.Jenkins和GitLab的安裝
工欲善其事,必先利其器 Jenkins的安裝可以看我之前的一篇文章:https://www.cnblogs.com/peyshine/p/12891935.html Gitlab的安裝推薦看下這篇文章:https://segmentfault.com/a/1190000021593151三.打通GitLab Webhooks與Jenkins流程
1.這裡先新建一個.net core應用程式,除了新增加了一個Jenkinsfile文件以外,其他沒有任何代碼的修改
pipeline{ agent any stages { stage('Build') { steps{ echo 'This is a build step' } } stage('Test') { steps{ echo 'This is a test step' } } stage('Deploy') { steps{ echo 'This is a deploy step' } } } }
然後將程式文件push到Gitlab上
2.在Jenkins系統管理,系統配置中,在Gitlab處添加相關信息





















四.接入Jenkinsfile,Dockerfile實現自動發佈
編寫Dockerfile如下:FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build COPY *.csproj ./app/ WORKDIR /app RUN dotnet restore COPY . ./ RUN dotnet publish -o out /p:PublishWithAspNetCoreTargetManifest="false" FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS runtime ENV ASPNETCORE_URLS http://+:80 WORKDIR /app COPY --from=build /app/out ./ ENTRYPOINT ["dotnet", "WebApplication_Jenkinsfile.dll"]編寫Jenkinsfile如下:
pipeline{ agent any stages { stage('Checkout') { steps{ git credentialsId: '85ca7e47-532e-4901-9828-50a8da071d16', url: 'http://xxx.gitlab.com/webapplication_jenkinsfile.git', branch:'master' echo '---This is a Checkout step---' } } stage('Build') { steps{ sh '''cd WebApplication_Jenkinsfile docker rmi -f docker_webapplication_test:1.0 docker build -t docker_webapplication_test:1.0 .''' echo '---This is a Build step---' } } stage('Run') { steps{ sh '''docker rm -f docker_webapplication_test docker run --name docker_webapplication_test -d -p 7489:80 docker_webapplication_test:1.0 ''' echo '---This is a run step---' } } } }
說明:
stages 必須,包括順序執行的一個或多個stage命令,在pipeline內僅能使用一次,通常位於agent/options後面 steps 必須,steps位於stage指令塊內部,包括一個或多個step。僅有一個step的情況下可以忽略關鍵字step及其{} 這裡為了演示,只添加了幾個核心的步驟,可以根據需要自行添加自動測試,郵件提醒等額外步驟 流水線語法,可以參照下圖中的示例步驟點擊後,可以生成腳本信息,上面Jenkinsfile中的git credentialsId信息就是在這裡生成的




