kbral
kbral

Reputation: 45

Building docker images inside a Jenkins container

I am using a jenkins container to execute a pipeline based on this Jenkinsfile:

pipeline {
agent any

tools {
    maven 'Maven 3.6.0'
    jdk 'jdk8'
}
stages {
    stage('Pull from git') {
        steps {
            checkout scm
        }
    }

    stage('Compile App') {
        steps {
            sh "mvn clean install"
        }
    }

    stage('Build da Imagem') {
        steps {
            script {
                docker.withTool("docker") {
                    def readyImage = docker.build("dummy-project/dummy-project-image", "./docker")
                    }
                }
            }
        }
    }
}

At the last stage i'm getting this Error when it tries to build the docker image. Is it possible build a docker image inside jenkins container?

Upvotes: 1

Views: 1210

Answers (1)

Nicola Ben
Nicola Ben

Reputation: 11377

Your pipeline executing agent doesn't communicate with docker daemon, so you need to configure it properly and you have three ways (the ones I know):

1) Provide your agent with a docker installation

2) Add a Docker installation from https:/$JENKINS_URL/configureTools/

3) If you use Kubernetes as orchestrator you may add a podTemplate definition at the beginning of your pipeline and then use it, here an example:

// Name of the application (do not use spaces)
def appName = "my-app"
// Start of podTemplate
def label = "mypod-${UUID.randomUUID().toString()}"
podTemplate(
  label: label,
  containers: [
    containerTemplate(
      name: 'docker',
      image: 'docker',
      command: 'cat',
      ttyEnabled: true)],
  volumes: [
    hostPathVolume(hostPath: '/var/run/docker.sock', mountPath: '/var/run/docker.sock'),
    hostPathVolume(hostPath: '/usr/bin/kubectl', mountPath: '/usr/bin/kubectl'),
    secretVolume(mountPath: '/etc/kubernetes', secretName: 'cluster-admin')],
  annotations: [
      podAnnotation(key: "development", value: appName)]
)
// End of podTemplate


[...inside your pipeline]

  container('docker') {
    stage('Docker Image and Push') {
      docker.withRegistry('https://registry.domain.it', 'nexus') {
      def img = docker.build(appName, '.')
      img.push('latest')
  }

I hope this helps you

Upvotes: 1

Related Questions