jenkins
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseJenkins
Jenkins
Build, test, and deploy applications using Jenkins, the leading open-source automation server.
使用Jenkins(领先的开源自动化服务器)构建、测试和部署应用程序。
When to Use This Skill
何时使用此技能
Use this skill when:
- Setting up Jenkins pipelines (declarative or scripted)
- Configuring Jenkins agents and executors
- Managing Jenkins plugins and security
- Creating shared libraries for pipeline reuse
- Integrating Jenkins with external tools
在以下场景使用此技能:
- 搭建Jenkins流水线(声明式或脚本式)
- 配置Jenkins代理和执行器
- 管理Jenkins插件与安全设置
- 创建用于流水线复用的共享库
- 将Jenkins与外部工具集成
Prerequisites
前提条件
- Jenkins server (2.x or later)
- Admin access to Jenkins
- Java 11+ on Jenkins server
- Basic Groovy understanding for pipelines
- Jenkins服务器(2.x或更高版本)
- Jenkins的管理员权限
- Jenkins服务器上安装Java 11+
- 具备Groovy基础知识以编写流水线
Declarative Pipeline
声明式流水线
Create in repository root:
Jenkinsfilegroovy
pipeline {
agent any
environment {
DOCKER_REGISTRY = 'registry.example.com'
APP_NAME = 'myapp'
}
stages {
stage('Build') {
steps {
sh 'npm ci'
sh 'npm run build'
}
}
stage('Test') {
steps {
sh 'npm test'
}
post {
always {
junit 'test-results/*.xml'
}
}
}
stage('Deploy') {
when {
branch 'main'
}
steps {
sh './deploy.sh'
}
}
}
post {
failure {
mail to: 'team@example.com',
subject: "Pipeline Failed: ${env.JOB_NAME}",
body: "Check console output at ${env.BUILD_URL}"
}
}
}在仓库根目录创建:
Jenkinsfilegroovy
pipeline {
agent any
environment {
DOCKER_REGISTRY = 'registry.example.com'
APP_NAME = 'myapp'
}
stages {
stage('Build') {
steps {
sh 'npm ci'
sh 'npm run build'
}
}
stage('Test') {
steps {
sh 'npm test'
}
post {
always {
junit 'test-results/*.xml'
}
}
}
stage('Deploy') {
when {
branch 'main'
}
steps {
sh './deploy.sh'
}
}
}
post {
failure {
mail to: 'team@example.com',
subject: "Pipeline Failed: ${env.JOB_NAME}",
body: "Check console output at ${env.BUILD_URL}"
}
}
}Agent Configuration
代理配置
Docker Agent
Docker代理
groovy
pipeline {
agent {
docker {
image 'node:20'
args '-v /tmp:/tmp'
}
}
stages {
stage('Build') {
steps {
sh 'npm ci && npm run build'
}
}
}
}groovy
pipeline {
agent {
docker {
image 'node:20'
args '-v /tmp:/tmp'
}
}
stages {
stage('Build') {
steps {
sh 'npm ci && npm run build'
}
}
}
}Kubernetes Agent
Kubernetes代理
groovy
pipeline {
agent {
kubernetes {
yaml '''
apiVersion: v1
kind: Pod
spec:
containers:
- name: node
image: node:20
command:
- sleep
args:
- infinity
- name: docker
image: docker:24-dind
securityContext:
privileged: true
'''
}
}
stages {
stage('Build') {
steps {
container('node') {
sh 'npm ci && npm run build'
}
}
}
}
}groovy
pipeline {
agent {
kubernetes {
yaml '''
apiVersion: v1
kind: Pod
spec:
containers:
- name: node
image: node:20
command:
- sleep
args:
- infinity
- name: docker
image: docker:24-dind
securityContext:
privileged: true
'''
}
}
stages {
stage('Build') {
steps {
container('node') {
sh 'npm ci && npm run build'
}
}
}
}
}Labeled Agents
标记代理
groovy
pipeline {
agent { label 'linux && docker' }
stages {
stage('Build') {
steps {
sh 'make build'
}
}
}
}groovy
pipeline {
agent { label 'linux && docker' }
stages {
stage('Build') {
steps {
sh 'make build'
}
}
}
}Parameters
参数配置
groovy
pipeline {
agent any
parameters {
string(name: 'BRANCH', defaultValue: 'main', description: 'Branch to build')
choice(name: 'ENVIRONMENT', choices: ['dev', 'staging', 'prod'], description: 'Target environment')
booleanParam(name: 'RUN_TESTS', defaultValue: true, description: 'Run tests?')
}
stages {
stage('Deploy') {
when {
expression { params.ENVIRONMENT == 'prod' }
}
steps {
sh "deploy.sh ${params.ENVIRONMENT}"
}
}
}
}groovy
pipeline {
agent any
parameters {
string(name: 'BRANCH', defaultValue: 'main', description: 'Branch to build')
choice(name: 'ENVIRONMENT', choices: ['dev', 'staging', 'prod'], description: 'Target environment')
booleanParam(name: 'RUN_TESTS', defaultValue: true, description: 'Run tests?')
}
stages {
stage('Deploy') {
when {
expression { params.ENVIRONMENT == 'prod' }
}
steps {
sh "deploy.sh ${params.ENVIRONMENT}"
}
}
}
}Credentials
凭证管理
Using Credentials
使用凭证
groovy
pipeline {
agent any
environment {
AWS_CREDS = credentials('aws-credentials')
DOCKER_CREDS = credentials('docker-hub')
}
stages {
stage('Deploy') {
steps {
withCredentials([
usernamePassword(
credentialsId: 'github-token',
usernameVariable: 'GH_USER',
passwordVariable: 'GH_TOKEN'
)
]) {
sh 'git push https://${GH_USER}:${GH_TOKEN}@github.com/repo.git'
}
}
}
}
}groovy
pipeline {
agent any
environment {
AWS_CREDS = credentials('aws-credentials')
DOCKER_CREDS = credentials('docker-hub')
}
stages {
stage('Deploy') {
steps {
withCredentials([
usernamePassword(
credentialsId: 'github-token',
usernameVariable: 'GH_USER',
passwordVariable: 'GH_TOKEN'
)
]) {
sh 'git push https://${GH_USER}:${GH_TOKEN}@github.com/repo.git'
}
}
}
}
}Parallel Stages
并行阶段
groovy
pipeline {
agent any
stages {
stage('Tests') {
parallel {
stage('Unit Tests') {
steps {
sh 'npm run test:unit'
}
}
stage('Integration Tests') {
steps {
sh 'npm run test:integration'
}
}
stage('E2E Tests') {
steps {
sh 'npm run test:e2e'
}
}
}
}
}
}groovy
pipeline {
agent any
stages {
stage('Tests') {
parallel {
stage('Unit Tests') {
steps {
sh 'npm run test:unit'
}
}
stage('Integration Tests') {
steps {
sh 'npm run test:integration'
}
}
stage('E2E Tests') {
steps {
sh 'npm run test:e2e'
}
}
}
}
}
}Shared Libraries
共享库
Library Structure
库结构
vars/
├── buildApp.groovy
├── deployApp.groovy
└── notifySlack.groovy
src/
└── com/example/
└── Pipeline.groovy
resources/
└── templates/
└── deployment.yamlvars/
├── buildApp.groovy
├── deployApp.groovy
└── notifySlack.groovy
src/
└── com/example/
└── Pipeline.groovy
resources/
└── templates/
└── deployment.yamlDefine Shared Step
定义共享步骤
groovy
// vars/buildApp.groovy
def call(Map config = [:]) {
def nodeVersion = config.nodeVersion ?: '20'
docker.image("node:${nodeVersion}").inside {
sh 'npm ci'
sh 'npm run build'
}
}groovy
// vars/buildApp.groovy
def call(Map config = [:]) {
def nodeVersion = config.nodeVersion ?: '20'
docker.image("node:${nodeVersion}").inside {
sh 'npm ci'
sh 'npm run build'
}
}Use Shared Library
使用共享库
groovy
@Library('my-shared-library') _
pipeline {
agent any
stages {
stage('Build') {
steps {
buildApp(nodeVersion: '20')
}
}
stage('Deploy') {
steps {
deployApp(environment: 'staging')
}
}
}
post {
failure {
notifySlack(channel: '#builds', status: 'FAILED')
}
}
}groovy
@Library('my-shared-library') _
pipeline {
agent any
stages {
stage('Build') {
steps {
buildApp(nodeVersion: '20')
}
}
stage('Deploy') {
steps {
deployApp(environment: 'staging')
}
}
}
post {
failure {
notifySlack(channel: '#builds', status: 'FAILED')
}
}
}Scripted Pipeline
脚本式流水线
groovy
node('linux') {
try {
stage('Checkout') {
checkout scm
}
stage('Build') {
docker.image('node:20').inside {
sh 'npm ci'
sh 'npm run build'
}
}
stage('Test') {
sh 'npm test'
}
if (env.BRANCH_NAME == 'main') {
stage('Deploy') {
sh './deploy.sh'
}
}
} catch (e) {
currentBuild.result = 'FAILURE'
throw e
} finally {
cleanWs()
}
}groovy
node('linux') {
try {
stage('Checkout') {
checkout scm
}
stage('Build') {
docker.image('node:20').inside {
sh 'npm ci'
sh 'npm run build'
}
}
stage('Test') {
sh 'npm test'
}
if (env.BRANCH_NAME == 'main') {
stage('Deploy') {
sh './deploy.sh'
}
}
} catch (e) {
currentBuild.result = 'FAILURE'
throw e
} finally {
cleanWs()
}
}Plugin Management
插件管理
Essential Plugins
必备插件
groovy
// Install via Jenkins CLI or init.groovy.d
def plugins = [
'workflow-aggregator', // Pipeline
'git', // Git integration
'docker-workflow', // Docker Pipeline
'kubernetes', // Kubernetes agent
'credentials-binding', // Credentials
'blueocean', // Blue Ocean UI
'job-dsl', // Job DSL
'configuration-as-code' // JCasC
]groovy
// Install via Jenkins CLI or init.groovy.d
def plugins = [
'workflow-aggregator', // Pipeline
'git', // Git integration
'docker-workflow', // Docker Pipeline
'kubernetes', // Kubernetes agent
'credentials-binding', // Credentials
'blueocean', // Blue Ocean UI
'job-dsl', // Job DSL
'configuration-as-code' // JCasC
]Configuration as Code
代码化配置(JCasC)
yaml
undefinedyaml
undefinedjenkins.yaml
jenkins.yaml
jenkins:
systemMessage: "Jenkins configured via JCasC"
numExecutors: 2
securityRealm:
local:
users:
- id: admin
password: ${ADMIN_PASSWORD}
authorizationStrategy:
globalMatrix:
permissions:
- "Overall/Administer:admin"
- "Overall/Read:authenticated"
credentials:
system:
domainCredentials:
- credentials:
- usernamePassword:
id: "docker-hub"
username: "user"
password: ${DOCKER_PASSWORD}
undefinedjenkins:
systemMessage: "Jenkins configured via JCasC"
numExecutors: 2
securityRealm:
local:
users:
- id: admin
password: ${ADMIN_PASSWORD}
authorizationStrategy:
globalMatrix:
permissions:
- "Overall/Administer:admin"
- "Overall/Read:authenticated"
credentials:
system:
domainCredentials:
- credentials:
- usernamePassword:
id: "docker-hub"
username: "user"
password: ${DOCKER_PASSWORD}
undefinedMultibranch Pipeline
多分支流水线
groovy
// Automatically discovers branches with Jenkinsfile
// Configure in Jenkins UI: New Item > Multibranch Pipeline
// Branch-specific behavior in Jenkinsfile
pipeline {
agent any
stages {
stage('Deploy') {
when {
anyOf {
branch 'main'
branch 'release/*'
}
}
steps {
sh './deploy.sh'
}
}
}
}groovy
// Automatically discovers branches with Jenkinsfile
// Configure in Jenkins UI: New Item > Multibranch Pipeline
// Branch-specific behavior in Jenkinsfile
pipeline {
agent any
stages {
stage('Deploy') {
when {
anyOf {
branch 'main'
branch 'release/*'
}
}
steps {
sh './deploy.sh'
}
}
}
}Common Issues
常见问题
Issue: Pipeline Syntax Errors
问题:流水线语法错误
Problem: Jenkinsfile fails to parse
Solution: Use Pipeline Syntax generator in Jenkins UI, validate with
jenkins-cli现象:Jenkinsfile解析失败
解决方案:使用Jenkins UI中的流水线语法生成器,或通过验证
jenkins-cliIssue: Agent Not Connecting
问题:代理无法连接
Problem: Build agents disconnect
Solution: Check agent logs, verify network connectivity, increase timeout settings
现象:构建代理断开连接
解决方案:检查代理日志,验证网络连通性,增加超时设置
Issue: Out of Memory
问题:内存不足
Problem: Jenkins crashes or builds fail with OOM
Solution: Increase heap size in , clean up old builds
JAVA_OPTS现象:Jenkins崩溃或构建因OOM失败
解决方案:在中增加堆内存,清理旧构建
JAVA_OPTSBest Practices
最佳实践
- Use declarative pipelines for most use cases
- Implement shared libraries for reusable code
- Store Jenkinsfile in source control
- Use credentials plugin for secrets management
- Implement proper cleanup in post blocks
- Configure build retention policies
- Use Blue Ocean for modern UI experience
- 大多数场景使用声明式流水线
- 实现共享库以复用代码
- 将Jenkinsfile存储在版本控制系统中
- 使用凭证插件管理密钥
- 在post块中实现适当的清理操作
- 配置构建保留策略
- 使用Blue Ocean获得现代化UI体验
Related Skills
相关技能
- github-actions - GitHub native CI/CD
- kubernetes-ops - K8s deployment target
- docker-management - Container builds
- github-actions - GitHub原生CI/CD工具
- kubernetes-ops - K8s部署目标
- docker-management - 容器构建