Introduction
Jenkins Pipeline is a suite of plugins that allows creating simple-to-complex build pipelines as code in Jenkins, using a Groovy-based domain-specific language.
Prerequisites
- Up and running Docker and Jenkins Server
Step 1: Generate Access Tokens
We need to generate the Access token for Github and DockerHub, Use the follwowing staps to get that.
For Github access token
- Login in GitHub Account
- Open Setting Section
- Go to the Developer Setting
- Click on Personal Access Token
- Generate New Token
- Selecting Permission
- click on Generate token
For DockerHub access token
- Login in DockerHub Account
- Click on User Profile Icon
- Go to the Account Setting
- Click on Security Section
- Click on New access token button
Step 2: Configure Access Token in Jenkins
We need to save the github and DokcerHub credtions with Jenkins
- Login Jenkins Server
- Click on Manage Jenkins
- Go to Seruity Section
- Click on Manage Credentials
- Go to Stores scoped to Jenkins and Click on System
- Click on Global credentials button
- Click on Add Credentials Button
- Select Kind with username with password
- Put your username, password (token) with ID
After saving the cred with Jenkins we need to use ID in Jenkins pipeline to call the creds :).
Step 3: Docker Build and Push with Pipeline
Create a Jenkins ‘sJob with name like BuildPush_Image and copy and paste the follwing code and you need to update the follwing things.
- Replace DockerHub Cred ID.
- Replace Github Repositoy and Branch with Github Cred ID
- Replace Docker registry URL
pipeline{
agent any
environment {
DOCKERHUB_CREDENTIALS=credentials('DockerHub')
}
stages {
stage("Git Clone"){
steps{
git branch: 'main', credentialsId: 'Github', url: 'https://github.com/aftab70/DockerImages.git'
}
}
stage('Build') {
steps {
sh 'docker build -t aftab70/custom_apache:${BUILD_NUMBER} .'
}
}
stage('Login') {
steps {
sh 'echo $DOCKERHUB_CREDENTIALS_PSW | docker login -u $DOCKERHUB_CREDENTIALS_USR --password-stdin'
}
}
stage('Push') {
steps {
sh 'docker push aftab70/custom_apache:${BUILD_NUMBER}'
}
}
}
post {
always {
sh 'docker logout'
}
}
}
Step 4: Testing Docker Image
We should get Jenkins Job output like this.
After Jenkins job success status, We can also verify the DockerHub Repository with build numbers.
Conclusion
We have successfully build and push docker image uisng jenkins pipeline, If you still have questions, please post them in the comments section below.
One thought on “Push a Docker Image To Docker Hub Using Jenkins”