1. 環境準備:安裝Java環境
Jenkins依賴Java運行時環境(JRE),需先在Debian系統上安裝OpenJDK 11(或更高版本)。執行以下命令完成安裝:
sudo apt update
sudo apt install -y openjdk-11-jdk
# 驗證Java安裝
java -version
確保輸出顯示Java版本信息,否則需檢查網絡或軟件源配置。
2. 安裝Jenkins:添加官方倉庫與安裝包
通過Jenkins官方倉庫安裝最新穩定版,避免第三方源的兼容性問題:
# 下載并添加Jenkins GPG密鑰(用于驗證軟件包完整性)
wget -q -O - https://pkg.jenkins.io/debian/jenkins.io.key | sudo apt-key add -
# 添加Jenkins官方軟件源
echo "deb http://pkg.jenkins.io/debian-stable binary/" | sudo tee /etc/apt/sources.list.d/jenkins.list
# 更新軟件包索引并安裝Jenkins
sudo apt update
sudo apt install -y jenkins
安裝完成后,Jenkins服務會自動啟動。
3. 啟動與基礎配置:解鎖Jenkins并設置管理員賬戶
首次訪問Jenkins需完成初始化配置:
sudo cat /var/lib/jenkins/secrets/initialAdminPassword
http://<服務器IP>:8080
,輸入上述密碼完成解鎖。4. 配置Jenkins:安裝必備插件與安全設置
為支持自動化部署,需安裝核心插件并調整安全配置:
https://mirrors.tuna.tsinghua.edu.cn/jenkins/updates/update-center.json
),加速插件下載。5. 創建自動化部署流水線:聲明式Pipeline與Jenkinsfile
采用聲明式Pipeline(推薦)定義自動化流程,將流水線腳本納入版本控制(如Git),實現“代碼即流水線”。
my-app-deploy
),選擇“Pipeline”,點擊“OK”。https://github.com/your-repo/my-app.git
),并通過“Credentials”添加Git訪問憑據(如SSH密鑰)。Jenkinsfile
,定義流水線的agent
(執行節點)、stages
(階段)及steps
(步驟)。示例如下:pipeline {
agent any
stages {
stage('Checkout') {
steps {
checkout scm // 拉取代碼(與SCM配置關聯)
}
}
stage('Build') {
steps {
sh 'mvn clean package' // Maven構建Java項目(根據項目類型調整命令)
}
}
stage('Test') {
steps {
sh 'python -m pytest tests/' // 運行單元測試(示例為Python項目)
}
}
stage('Deploy') {
steps {
sshPublisher( // 通過SSH將構建產物部署到遠程服務器
publishers: [
sshPublisherDesc(
configName: 'production-server', // 事先配置的SSH服務器別名(Manage Jenkins → Credentials → System → Global credentials)
transfers: [
sshTransfer(
sourceFiles: 'target/*.jar', // 本地構建產物路徑
removePrefix: 'target', // 移除前綴后上傳
remoteDirectory: '/opt/app/deploy' // 遠程服務器部署目錄
)
],
usePromotionTimestamp: false,
useWorkspaceInPromotion: false,
verbose: true
)
]
)
}
}
}
post {
always {
echo 'Deployment process completed.' // 構建完成后輸出日志
}
success {
mail to: 'team@example.com', subject: "Build Success: ${currentBuild.fullDisplayName}", body: "The deployment of ${currentBuild.fullDisplayName} succeeded." // 發送成功郵件
}
failure {
mail to: 'team@example.com', subject: "Build Failed: ${currentBuild.fullDisplayName}", body: "The deployment of ${currentBuild.fullDisplayName} failed." // 發送失敗郵件
}
}
}
注:需提前在Jenkins中配置SSH服務器憑據(Manage Jenkins → Credentials → System → Global credentials → Add Credentials),并創建對應的configName
(如production-server
)。6. 觸發自動化部署:Webhook或定時任務
實現代碼變更自動觸發流水線,常見方式有兩種:
http://<服務器IP>:8080/github-webhook/
),選擇“Just the push event”,保存后,每次代碼推送都會自動觸發Jenkins流水線。H/5 * * * *
表示每5分鐘檢查一次代碼變更),定期觸發流水線。7. 可選優化:高可用性與監控
docker run -d --name jenkins-agent \
-v /var/run/docker.sock:/var/run/docker.sock \
-e JENKINS_URL=http://master-ip:8080 \
jenkins/jenkins-agent
其中master-ip
為Jenkins Master服務器的IP地址。http://your-service.com/health
),通過Jenkins的“Execute shell”步驟或郵件插件發送報警通知(如企業微信、釘釘)。