Tuesday, 26 May 2020

Execute commands inside Docker container in Jenkins

Run Jenkins Automation Server as Docker Image – Rob Juurlink

This guide will show you how to perform some build steps or command inside a Docker container, using Declarative Pipelines in Jenkins.

Imagine you have to build a special application, which requires lots of libraries and dependencies, at specific versions, and you can't install them on your Jenkins machines.
How to build it?

Using a Docker container!

First of all, you need to install the Docker Pipeline plugin:

To use the plugin with a Declarative pipeline, add this stage:

stage('Run command inside a container') {
  steps {
    script {
      withDockerContainer("my-custom-image:1.0") {
        echo 'This command is executed inside the container!'
      }
    }
  }
}

Takes the image my-custom-image:1.0 which must already have been pulled locally, and starts a container based on that image. Runs all nested steps inside that container. The workspace is mounted read-write into the container.

Example with Python:

pipeline {
  agent any 
  stages {
   
    stage('Clone sources') {
      steps {
        git credentialsId: 'git-creds', url: 'https://git.example.com/myrepo.git'
      }        
    }

    //build a Docker image with a Dockerfile from sources
    stage("Build Docker images") {
      steps {
        script {
          docker_image_dev = docker.build("my-custom-python:3.6")
        }
      }
    }

    //Run tests inside a container based on previous image
    stage('Run Tests: Coverage') {
      steps {
        script {
          withDockerContainer("my-custom-python:3.6") {
            sh 'pwd'
            sh 'pylint source | tee test/results/pylint.txt'
          }
        }
      }
    }

  }
}


No comments:

Post a Comment