Jenkins Pipelines: Building a docker image

Published: Tuesday, 30 June 2020

Below is an example Jenkinsfile that builds a Docker image and pushes it to a registry.

pipeline {
    agent any
    
    stages {
    
        stage('build') {
            steps {
                script {
                    dockerImage = docker.build("magicmonster/example", ".")
                }
            }
        }
    
        stage('publish') {
            steps {
                echo 'Pushing to registry'
                script {
                    docker.withRegistry('https://registry.example.com/', 'registry-credential-id') {
                        dockerImage.push()
                    }
                }
            }
        }
    }
}

The docker global variable can be used to build an image.

The first usage is the equivalent of running.

docker build --tag magicmonster/example .

The resulting image is referenced by the dockerImage variable.

To publish the image to a registry, use the withRegistry method. Before using this, there must be

  • a private docker registry configured (or docker hub)
  • registry credentials stored within Jenkins. The Kind of credential should be a Username with password.

In the above example https://registry.example.com/ is the registry’s URL and registry-credential-id is the Jenkins credential ID.

References