Jenkins Pipelines: Building a docker image

Published: Tuesday, 30 June 2020
jenkins docker

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

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

References