In this blog, we will see how to establish the connection between jenkins and dockerhub and put your dockerimage to docerhub.
Let's learn easily and slowly one by one step which is explained very clearly and you just follow it as is.
Login to your jenkins console and click on Manage Jenkins.
In the security, go to Credentials
Click on System
Click on Global credentials (unrestricted)
Click on +Add Credentials
Add your DockerHub Credentials here, Kind:Username with password, Scope:Global, Username:DockerUsername, Password:DockerPassword, ID:dockerhub, This is an important field to be mentioned in the PipelineCode(so remember it and put it meaningfully).
Now your DockerHub Creds are added and you can see it below.
Let's start putting it in the docker file
Here, We are using the same steps as configured in last bolg https://kshitijaa.hashnode.dev/jenkins-pipeline and in the pipeline adding below stage
stage("Push DockerImage to DockrHub")
Here withCredentials is a function and it is using credentialsId to store and pass the credentials to Push DockerImage to DockerHub.
My Jenkins Pipeline look like:
pipeline {
agent any
stages{
stage("Git Clone"){
steps{
git url: "https://github.com/kshitijabartakke/calculategrowth.git", branch: "main"
}
}
stage("Create Docker Image"){
steps{
echo "Build and Test"
withCredentials([usernamePassword(credentialsId:"dockerhub",passwordVariable:"dockerHubPass",usernameVariable:"dockerHubUser")]){
sh "docker login -u ${env.dockerHubUser} -p ${env.dockerHubPass}"
sh "docker build -t kshitibartakke/calculategrowth ."
}
}
}
stage("Push DockerImage to DockrHub"){
steps{
withCredentials([usernamePassword(credentialsId:"dockerhub",passwordVariable:"dockerHubPass",usernameVariable:"dockerHubUser")]){
sh "docker login -u ${env.dockerHubUser} -p ${env.dockerHubPass}"
sh "docker images"
sh "docker push kshitibartakke/calculategrowth:latest"
}
}
}
stage("Deploy Using DOcker Compose"){
steps{
sh "docker-compose down && docker-compose up -d"
}
}
}
}