温馨提示×

Jenkins如何在Ubuntu上实现多任务并行

小樊
35
2025-12-08 13:01:46
栏目: 智能运维

在 Ubuntu 上,Jenkins 可通过多 Executors、Pipeline 并行阶段、多节点分布式构建以及并发构建 Job 四种方式实现多任务并行。下面给出可直接落地的配置方法与示例。


一、并行方式总览与选择

方式 作用范围 适用场景 关键配置点
单机多 Executors 同一 Ubuntu 节点 轻量任务、快速构建、单机资源利用 设置 Manage Jenkins → Configure System → # of executors
Pipeline parallel 阶段 单个流水线内部 多模块/多环境同时构建与测试 使用 parallel { stage … }
多节点分布式构建 多个 Agent/节点 大规模构建、隔离环境、横向扩展 Manage Nodes and Clouds 添加节点,使用 标签 调度
并发构建多个 Job 多个 Job 实例 不同项目/分支同时跑 允许并发构建(默认支持),必要时用 Throttle Concurrent Builds 插件限流

二、单机多 Executors 并行

  • 进入 Manage Jenkins → Configure System,将 # of executors 调整为不超过 CPU 物理核心数(超线程可按需适度上调,但避免内存争用)。
  • 保存后,同一节点即可同时运行多个构建实例,适合快速任务与轻量流水线。
  • 提示:每个并发构建拥有独立工作区,Jenkins 会在目录名后追加 @2、@3 等后缀以避免冲突。

三、Pipeline 并行阶段

  • 在声明式流水线中使用 parallel 将多个阶段并行化,常用于“前端/后端”或“多模块”同时构建与测试。
  • 示例(可直接粘贴到 Jenkinsfile):
pipeline {
  agent any
  stages {
    stage('并行构建与测试') {
      parallel {
        stage('构建前端') {
          steps { echo 'Building frontend...' }
        }
        stage('构建后端') {
          steps { echo 'Building backend...' }
        }
        stage('并行测试集A') {
          steps {
            script {
              timeout(time: 5, unit: 'MINUTES') {
                echo 'Running tests A...'
                // sh 'run-tests-a.sh'
              }
            }
          }
        }
        stage('并行测试集B') {
          steps {
            script {
              timeout(time: 5, unit: 'MINUTES') {
                echo 'Running tests B...'
                // sh 'run-tests-b.sh'
              }
            }
          }
        }
      }
    }
  }
  post {
    success { echo '✅ 全部完成' }
    failure { echo '❌ 存在失败或超时' }
  }
}
  • 建议为可能卡住的脚本或测试套件添加 timeout,避免流水线无限阻塞。

四、多节点分布式构建

  • 添加节点:进入 Manage Jenkins → Manage Nodes and Clouds → New Node,配置 标签(Label)、远程工作目录、启动方式(如 SSH)。
  • 在 Job 配置中使用 Restrict where this project can be run 指定节点 标签,或在 Pipeline 中使用 agent { label ‘your-label’ }
  • 这样可将构建分发到多台 Ubuntu 机器或多环境,实现横向扩展与资源隔离。

五、并发构建多个 Job 与扩展实践

  • 同一 Job 的并发构建:Jenkins 默认允许同一 Job 同时运行多个实例(每个实例有独立工作区,目录名后缀 @N),适合不同分支/参数同时触发。
  • 如需限流或配额控制,可安装 Throttle Concurrent Builds 插件,在 Job 配置中设置最大并发数。
  • 批量创建/编排多个并行任务:使用 Job DSL 脚本批量生成 Pipeline Job,统一从 Jenkinsfile 拉取脚本,便于规模化治理。
  • 示例(Job DSL 片段):
jobs {
  pipelineJob('Parallel-Job-1') {
    definition {
      cpsScm {
        scm {
          git {
            remote { url('https://github.com/your-org/your-repo.git') }
            credentialsId('your-credentials-id')
          }
        }
        scriptPath('Jenkinsfile')
      }
    }
  }
  pipelineJob('Parallel-Job-2') {
    definition {
      cpsScm {
        scm {
          git {
            remote { url('https://github.com/your-org/your-repo.git') }
            credentialsId('your-credentials-id')
          }
        }
        scriptPath('Jenkinsfile')
      }
    }
  }
}
  • 适用场景:多项目/多仓库同时构建、按团队或业务线隔离流水线。

0