13

我有一个具有多个阶段的管道,我想在仅“n”个阶段而不是所有阶段之间重用一个 docker 容器:

pipeline {
   agent none

   stages {
       stage('Install deps') {
            agent {
                docker { image 'node:10-alpine' }
            }

            steps {
                sh 'npm install'
            }
        }

       stage('Build, test, lint, etc') {
            agent {
                docker { image 'node:10-alpine' }
            }

            parallel {
                stage('Build') {
                    agent {
                        docker { image 'node:10-alpine' }
                    }

                    // This fails because it runs in a new container, and the node_modules created during the first installation are gone at this point
                    // How do I reuse the same container created in the install dep step?
                    steps {
                        sh 'npm run build'
                    }
                }

                stage('Test') {
                    agent {
                        docker { image 'node:10-alpine' }
                    }

                    steps {
                        sh 'npm run test'
                    }
                }
            }
        }


        // Later on, there is a deployment stage which MUST deploy using a specific node,
        // which is why "agent: none" is used in the first place

   }
}
4

3 回答 3

18

请参阅Jenkins Pipeline docker代理的重用节点选项:
https ://jenkins.io/doc/book/pipeline/syntax/#agent

pipeline {
  agent any

  stages {
    stage('NPM install') {
      agent {
        docker {
          /*
           * Reuse the workspace on the agent defined at top-level of
           * Pipeline, but run inside a container.
           */
          reuseNode true
          image 'node:12.16.1'
        }
      }

      environment {
        /*
         * Change HOME, because default is usually root dir, and
         * Jenkins user may not have write permissions in that dir.
         */
        HOME = "${WORKSPACE}"
      }

      steps {
        sh 'env | sort'
        sh 'npm install'
      }
    }
  } 
}
于 2020-04-13T22:12:14.443 回答
8

您可以使用脚本化管道,您可以在一个步骤中放置多个stage步骤docker,例如

node {
  checkout scm
  docker.image('node:10-alpine').inside {
    stage('Build') {
       sh 'npm run build'
     }
     stage('Test') {
       sh 'npm run test'
     }
  }
}

(代码未经测试)

于 2018-05-21T21:40:14.373 回答
3

对于声明式管道,一种解决方案是在项目的根目录中使用 Dockerfile。例如

Dockerfile

FROM node:10-alpine
// Further Instructions

詹金斯文件

pipeline{

    agent {
        dockerfile true
    }
    stage('Build') {
        steps{
            sh 'npm run build'
        }
    }
     stage('Test') {
        steps{
            sh 'npm run test'
        }
    }
}
于 2019-04-13T22:29:39.333 回答