Reuse agent (docker container) in Jenkins between multiple stages Reuse agent (docker container) in Jenkins between multiple stages jenkins jenkins

Reuse agent (docker container) in Jenkins between multiple stages


See reuseNode option for Jenkins Pipeline docker agent:
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'      }    }  } }


You can use scripted pipelines, where you can put multiple stage steps inside a docker step, e.g.

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

(code untested)


For Declarative pipeline, one solution can be to use Dockerfile in the root of the project. For e.g.

Dockerfile

FROM node:10-alpine// Further Instructions

Jenkinsfile

pipeline{    agent {        dockerfile true    }    stage('Build') {        steps{            sh 'npm run build'        }    }     stage('Test') {        steps{            sh 'npm run test'        }    }}