Ubuntu 上自定义 Jenkins 部署配置
一 环境与基础安装
二 核心组件与凭据配置
三 自定义部署流水线
任务类型与源码管理:
声明式 Jenkinsfile 示例(SSH 部署到远程主机,含条件与通知)
pipeline {
agent any
environment {
PROD_SERVER = 'prod.example.com'
DEPLOY_DIR = '/var/www/your-app'
SSH_CREDENTIALS = credentials('prod-ssh-key')
}
stages {
stage('Checkout') {
steps { git branch: 'main', url: 'https://github.com/your-repo/your-app.git' }
}
stage('Build') {
steps { sh 'mvn clean package -DskipTests' }
}
stage('Test') {
steps { sh 'mvn test'; junit '**/target/surefire-reports/*.xml' }
}
stage('Deploy to Production') {
when { branch 'main' }
steps {
sshagent([SSH_CREDENTIALS]) {
sh """
scp target/*.war ${SSH_CREDENTIALS}@${PROD_SERVER}:${DEPLOY_DIR}/app.war
ssh ${SSH_CREDENTIALS}@${PROD_SERVER} "cd ${DEPLOY_DIR} && sudo systemctl restart your-app.service"
"""
}
}
}
}
post {
success {
slackSend channel: '#deploy-notifications',
message: "Deployment to Production succeeded: ${env.JOB_NAME} #${env.BUILD_NUMBER}"
}
failure {
mail to: 'team@example.com',
subject: 'Deployment Failed',
body: "Job ${env.JOB_NAME} failed on build #${env.BUILD_NUMBER}"
}
}
}
其他常见方式:
四 触发器与自动化
五 进阶与运维优化
jenkins:
systemMessage: "Configured by JCasC"
tool:
git:
installations:
- name: git
home: /usr/bin/git
credentials:
system:
domainCredentials:
- credentials:
- basicSSHUserPrivateKey:
scope: SYSTEM
id: ssh_with_passphrase_provided
username: deploy
passphrase: ${SSH_KEY_PASSWORD}
privateKeySource:
directEntry:
privateKey: ${SSH_PRIVATE_KEY}