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
latesttag.
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
How to Deploy to Amazon ECS With JenkinsDeploy a new container image to an Amazon ECS service from a Jenkins Declarative Pipeline by registering a ta…
How to Deploy to Kubernetes With kubectl in JenkinsDeploy to a Kubernetes cluster from a Jenkins Declarative Pipeline by binding a kubeconfig with withKubeConfi…