Skip to content
Latchkey

How to Build and Push a Docker Image in Jenkins

Use the Docker Pipeline plugin to build the image, then authenticate and push inside docker.withRegistry.

Call docker.build to produce a tagged image, then wrap the push in docker.withRegistry(url, credentialsId) so the daemon is authenticated for the push.

Steps

  • Build the image with docker.build("repo:tag").
  • Authenticate to the registry with docker.withRegistry.
  • Push the build tag and, on main, a latest tag.

Pipeline

Jenkinsfile
pipeline {
  agent any
  stages {
    stage('Build and Push') {
      steps {
        script {
          def img = docker.build("myorg/api:${env.BUILD_NUMBER}")
          docker.withRegistry('https://registry.example.com', 'registry-creds') {
            img.push()
            img.push('latest')
          }
        }
      }
    }
  }
}

Gotchas

  • The agent needs Docker and the Docker Pipeline plugin installed.
  • For Docker Hub pass https://index.docker.io/v1/ as the registry URL.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →