跳到主要内容

Jenkins 速查表

快速查阅 Jenkins 常用命令、配置和语法。

Java 版本要求​

支持的 Java 版本LTS 版本Weekly 版本
Java 21 或 Java 25-2.545+
Java 17、21 或 252.541.1+2.534+
Java 17 或 Java 212.479.1+2.463+
Java 11、17 或 212.426.1+2.419+
Java 11 或 172.361.1+2.357+
Java 8、11 或 172.346.1+2.340+

重要:Java 17 支持将于 2026 年 3 月 31 日后结束,推荐使用 Java 21(Eclipse Temurin)。

服务管理命令​

Linux 系统服务​

# 启动 Jenkins
sudo systemctl start jenkins

# 停止 Jenkins
sudo systemctl stop jenkins

# 重启 Jenkins
sudo systemctl restart jenkins

# 查看状态
sudo systemctl status jenkins

# 查看日志
sudo journalctl -u jenkins -f
sudo tail -f /var/log/jenkins/jenkins.log

Docker 命令​

# 运行 Jenkins
docker run -d \
--name jenkins \
-p 8080:8080 \
-p 50000:50000 \
-v jenkins_home:/var/jenkins_home \
jenkins/jenkins:lts

# 查看日志
docker logs -f jenkins

# 获取初始密码
docker exec jenkins cat /var/jenkins_home/secrets/initialAdminPassword

# 进入容器
docker exec -it jenkins bash

# 重启容器
docker restart jenkins

Pipeline 语法速查​

基本结构​

pipeline {
agent any

environment {
VAR = 'value'
}

options {
timeout(time: 1, unit: 'HOURS')
}

stages {
stage('Build') {
steps {
echo 'Building...'
}
}
}

post {
always {
cleanWs()
}
}
}

Agent 配置​

// 任意节点
agent any

// 指定标签
agent { label 'linux' }

// Docker 容器
agent {
docker {
image 'maven:3.9-eclipse-temurin-21'
args '-v $HOME/.m2:/root/.m2'
}
}

// Kubernetes Pod
agent {
kubernetes {
yaml '''
apiVersion: v1
kind: Pod
spec:
containers:
- name: maven
image: maven:3.9-eclipse-temurin-21
command: ['cat']
tty: true
'''
}
}

// 阶段级 Agent
agent none
stages {
stage('Build') {
agent { label 'linux' }
steps { ... }
}
}

参数类型​

parameters {
string(name: 'BRANCH', defaultValue: 'main', description: '分支名称')
choice(name: 'ENV', choices: ['dev', 'test', 'prod'], description: '环境')
booleanParam(name: 'SKIP_TESTS', defaultValue: false, description: '跳过测试')
text(name: 'DESC', defaultValue: '', description: '描述')
password(name: 'SECRET', description: '密钥')
file(name: 'FILE', description: '文件')
}

When 条件​

when { branch 'main' }
when { environment name: 'ENV', value: 'prod' }
when { expression { params.DEPLOY == true } }
when { tag 'v*' }
when { changeset '**/*.js' }
when { triggeredBy 'TimerTrigger' }

// 组合条件
when {
allOf {
branch 'main'
expression { params.RELEASE }
}
}

when {
anyOf {
branch 'main'
branch 'release/*'
}
}

when {
not { branch 'develop' }
}

// 在分配 Agent 前评估条件(节省资源)
when {
beforeAgent true
expression { params.BUILD_NEEDED }
}

// 在等待用户输入前评估条件
when {
beforeInput true
branch 'main'
}

并行执行​

stage('Tests') {
parallel {
stage('Unit') {
steps { sh 'npm run test:unit' }
}
stage('Integration') {
steps { sh 'npm run test:integration' }
}
}
failFast true // 任一失败立即终止其他
}

Matrix 构建​

stage('Matrix Test') {
matrix {
axes {
axis {
name 'PLATFORM'
values 'linux', 'windows', 'macos'
}
axis {
name 'JAVA'
values '11', '17', '21'
}
}
excludes {
exclude {
axis { name 'PLATFORM'; values 'macos' }
axis { name 'JAVA'; values '11' }
}
}
agent { label "${PLATFORM}" }
stages {
stage('Build') {
steps { sh './build.sh' }
}
stage('Test') {
steps { sh './test.sh' }
}
}
}
}

Post 条件​

post {
always { } // 总是执行
success { } // 成功时执行
failure { } // 失败时执行
unstable { } // 不稳定时执行
aborted { } // 中止时执行
changed { } // 状态变化时执行
fixed { } // 从失败变为成功
regression { } // 从成功变为失败
}

常用步骤​

// Shell 命令
sh 'command'
sh '''多行命令'''

// Windows
bat 'command'
powershell 'command'

// 输出
echo 'message'

// Git 操作
git 'https://github.com/user/repo.git'
git branch: 'main', url: 'https://github.com/user/repo.git'

// 归档产物
archiveArtifacts artifacts: 'target/*.jar', fingerprint: true

// 测试报告
junit 'target/surefire-reports/*.xml'

// 清理工作空间
cleanWs()

// 超时
timeout(time: 30, unit: 'MINUTES') { sh 'command' }

// 重试
retry(3) { sh 'flaky-command' }

// 等待输入
input message: 'Continue?'

// 错误处理
catchError(buildResult: 'SUCCESS', stageResult: 'UNSTABLE') {
sh 'might-fail'
}

warnError('Optional step failed') {
sh 'optional-command'
}

脚本块​

script {
// 条件判断
if (env.BRANCH_NAME == 'main') {
echo 'Main branch'
}

// 循环
for (int i = 0; i < 10; i++) {
echo "Step ${i}"
}

// 异常处理
try {
sh 'risky-command'
} catch (Exception e) {
echo "Error: ${e.message}"
}

// 动态并行
def tests = [:]
['unit', 'integration', 'e2e'].each { type ->
tests[type] = {
sh "npm run test:${type}"
}
}
parallel tests
}

环境变量​

内置变量​

变量说明示例
BUILD_NUMBER构建编号42
BUILD_URL构建 URLhttp://jenkins/job/myjob/42/
JOB_NAME任务名称my-project
WORKSPACE工作空间/var/jenkins/workspace/my-project
NODE_NAME节点名称agent-01
BRANCH_NAME分支名(多分支)main, PR-42
CHANGE_IDPR 编号42
GIT_COMMITGit 提交a1b2c3d4
GIT_BRANCHGit 分支origin/main

定义环境变量​

environment {
// 静态值
APP_NAME = 'my-app'

// 凭据
DB_PASSWORD = credentials('db-password')

// 动态值
BUILD_DATE = sh(script: 'date +%Y%m%d', returnStdout: true).trim()

// 组合
FULL_NAME = "${APP_NAME}-${BUILD_NUMBER}"
}

// 使用
echo "${env.APP_NAME}"
sh 'echo $APP_NAME'

凭据使用​

// 环境变量方式
environment {
CREDS = credentials('credential-id')
// 使用: ${CREDS_USR} 和 ${CREDS_PSW}
}

// withCredentials 包装器
withCredentials([
usernamePassword(
credentialsId: 'cred-id',
usernameVariable: 'USER',
passwordVariable: 'PASS'
)
]) {
sh 'echo $USER:$PASS'
}

// SSH Agent
sshagent(['ssh-key-id']) {
sh 'git clone [email protected]:user/repo.git'
}

// Secret 文本
withCredentials([string(credentialsId: 'api-token', variable: 'TOKEN')]) {
sh "curl -H 'Authorization: Bearer $TOKEN' https://api.example.com"
}

// Secret 文件
withCredentials([file(credentialsId: 'config-file', variable: 'CONFIG')]) {
sh "cat $CONFIG"
}

Docker 集成​

// 构建镜像
docker.build("my-image:${env.BUILD_NUMBER}")

// 在容器内执行
docker.image('maven:3.9-eclipse-temurin-21').inside {
sh 'mvn clean package'
}

// 推送到仓库
docker.withRegistry('https://registry.example.com', 'credentials-id') {
docker.image('my-image').push('latest')
}

// 使用 Dockerfile
docker.build('my-image', '--build-arg VERSION=1.0 .')

常用插件​

源码管理​

插件功能
Git PluginGit 集成
GitHub Branch SourceGitHub 多分支/Org
GitLab Branch SourceGitLab 多分支/Org
Bitbucket Branch SourceBitbucket 集成

构建工具​

插件功能
Maven IntegrationMaven 构建
Gradle PluginGradle 构建
NodeJS PluginNode.js 支持
Docker PipelineDocker 集成

部署​

插件功能
KubernetesK8s 集成
Publish Over SSHSSH 部署
AWS StepsAWS 集成

通知​

插件功能
Email Extension邮件通知
Slack NotificationSlack 通知
DingTalk钉钉通知

代码质量​

插件功能
SonarQube Scanner代码扫描
Warnings Next Generation编译警告
Code Coverage API覆盖率报告

定时表达式​

Cron 语法​

┌───────────── 分钟 (0-59)
│ ┌───────────── 小时 (0-23)
│ │ ┌───────────── 日期 (1-31)
│ │ │ ┌───────────── 月份 (1-12)
│ │ │ │ ┌───────────── 星期 (0-7)
│ │ │ │ │
* * * * *

常用示例​

triggers {
// 每15分钟
cron('H/15 * * * *')

// 每小时
cron('H * * * *')

// 每天凌晨2点
cron('H 2 * * *')

// 工作日早上8点
cron('H 8 * * 1-5')

// 每周日晚上
cron('H H(0-2) * * 0')

// 轮询 SCM(不推荐)
pollSCM('H/5 * * * *')
}

配置文件路径​

文件路径
主配置$JENKINS_HOME/config.xml
任务配置$JENKINS_HOME/jobs/[job]/config.xml
用户配置$JENKINS_HOME/users/[user]/config.xml
插件目录$JENKINS_HOME/plugins/
工作空间$JENKINS_HOME/workspace/
凭据$JENKINS_HOME/credentials.xml

REST API​

# 获取任务列表
curl -X GET http://jenkins/api/json

# 触发构建
curl -X POST http://jenkins/job/my-job/build

# 带参数构建
curl -X POST "http://jenkins/job/my-job/buildWithParameters?BRANCH=main"

# 获取构建信息
curl -X GET http://jenkins/job/my-job/lastBuild/api/json

# 获取控制台输出
curl -X GET http://jenkins/job/my-job/lastBuild/consoleText

# 带 CSRF Token 的请求
CRUMB=$(curl -s 'http://jenkins/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)' -u user:token)
curl -X POST -H "$CRUMB" http://jenkins/job/my-job/build -u user:token

故障排查​

常见问题​

# 端口被占用
sudo netstat -tulpn | grep 8080
# 修改端口
sudo nano /etc/default/jenkins
# HTTP_PORT=8081

# 内存不足
sudo nano /etc/default/jenkins
# JAVA_OPTS="-Xmx2048m -Xms512m"

# 权限问题
sudo chown -R jenkins:jenkins /var/lib/jenkins
sudo usermod -aG docker jenkins

# 磁盘空间
df -h
du -sh /var/lib/jenkins/workspace/* | sort -hr | head -10

日志位置​

# 系统日志
/var/log/jenkins/jenkins.log

# systemd 日志
journalctl -u jenkins -f

# Docker 日志
docker logs -f jenkins

共享库​

使用​

// 加载库
@Library('my-lib') _
@Library('[email protected]') _

// 动态加载
library 'my-lib@main'

全局变量结构​

vars/
├── myStep.groovy # def call(...) { }
└── myStep.txt # 文档

最佳实践清单​

安全​

  • 启用安全矩阵授权
  • 使用凭据管理敏感信息
  • 定期更新 Jenkins 和插件
  • 启用 CSRF 保护
  • 使用 HTTPS
  • 禁用内置节点构建(设置执行器为 0)
  • 确保 Agent→Controller 访问控制已启用(2.326+ 默认启用)

性能​

  • 控制器不执行构建
  • 合理配置执行器数量
  • 启用构建丢弃策略
  • 定期清理工作空间
  • 使用 Pipeline 代替 Freestyle

维护​

  • 定期备份 JENKINS_HOME
  • 监控磁盘空间
  • 配置日志轮转
  • 文档化 Pipeline
  • 使用共享库复用代码

Pipeline​

  • 使用声明式 Pipeline
  • Jenkinsfile 放入版本控制
  • 合理设置超时和重试
  • 使用 when 控制条件执行
  • 并行化独立任务