如何在单个Docker容器内完整运行Jenkins流水线的全部阶段
流水线全程复用单个容器的实现方案
完全可以实现该需求,主流CI/CD平台均支持容器复用逻辑,无需为每个阶段单独启动容器,也不需要额外传递临时文件制品。
通用实现逻辑
不依赖特定CI平台的原生脚本实现方案:
- 流水线初始化阶段以后台 daemon 模式启动目标容器,同时将当前流水线工作目录挂载到容器内固定路径,保证宿主机和容器内文件实时同步
- 后续所有阶段的命令都通过
docker exec调用已经启动的容器执行,无需创建新容器 - 全流程执行完成后,统一销毁容器清理资源
通用脚本示例:
# 1. 初始化阶段:启动Terraform常驻容器 docker run -d --name tf-runner -v $(pwd):/workspace -w /workspace hashicorp/terraform:latest tail -f /dev/null # 2. 各阶段直接调用已有容器执行命令 # 执行init docker exec tf-runner terraform init # 执行plan docker exec tf-runner terraform plan -out=tfplan # 执行apply docker exec tf-runner terraform apply tfplan # 3. 流水线结束后销毁容器 docker rm -f tf-runner
主流CI平台原生配置方案
大部分CI平台已经封装了容器复用能力,不需要手动执行docker命令,直接配置即可生效:
- GitLab CI:在全局声明
image字段,所有阶段默认复用同一个容器实例# 全局声明运行镜像 image: hashicorp/terraform:latest stages: - init - plan - apply tf_init: stage: init script: - terraform init tf_plan: stage: plan script: - terraform plan -out=tfplan tf_apply: stage: apply script: - terraform apply tfplan - GitHub Actions:在workflow全局声明
container字段,所有步骤都会在指定容器内运行name: Terraform部署 on: push # 全局指定运行容器 container: image: hashicorp/terraform:latest jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - run: terraform init - run: terraform plan -out=tfplan - run: terraform apply tfplan - Jenkins:使用Pipeline的
docker.image().inside()包裹所有阶段,全程复用同一个容器pipeline { agent any stages { stage('Terraform部署') { agent { docker { image 'hashicorp/terraform:latest' } } stages { stage('Init') { steps { sh 'terraform init' } } stage('Plan') { steps { sh 'terraform plan -out=tfplan' } } stage('Apply') { steps { sh 'terraform apply tfplan' } } } } } }
注意事项
- 容器启动时需要把云厂商凭证、Terraform状态存储密钥等环境变量一并传入,避免每个步骤重复配置
- 无需额外保存plan文件作为跨阶段制品,同容器内的文件会全程保留,可直接读取
- 流水线执行失败时要补充容器销毁逻辑,避免残留无用后台容器占用资源
内容的提问来源于stack exchange,提问作者Flow
相关产品推荐
相关产品推荐

