DEV Community

Cover image for Build and Push Docker images to Docker Hub using Jenkins Pipeline
Kannan
Kannan

Posted on

Build and Push Docker images to Docker Hub using Jenkins Pipeline

  • Create a Git Repository named "dockerhub_jenkins" with Readme.md

  • Clone the repo to local machine and add the below required files

  • Create Dockerfile and image to run

FROM ubuntu:22.04
ENV DEBIAN_FRONTEND=noninteractive
RUN apt update
RUN apt install apache2 -y
RUN apt install apache2-utils -y
RUN apt clean
COPY index.html /var/www/html
EXPOSE 80
CMD ["apache2ctl","-D","FOREGROUND"]
Enter fullscreen mode Exit fullscreen mode
  • Create Jenkins file
kannan@kannan-PC:~/dockerhub_jenkins$ cat Jenkinsfile 
pipeline {
  agent any
  options {
    buildDiscarder(logRotator(numToKeepStr: '5'))
  }
  environment {
    DOCKERHUB_CREDENTIALS = credentials('kannanb95-dockerhub')
  }
  stages {
    stage('Build') {
      steps {
        sh 'docker build -t kannanb95/kaniyam:latest .'
      }
    }
    stage('Login') {
      steps {
        sh 'echo $DOCKERHUB_CREDENTIALS_PSW | docker login -u $DOCKERHUB_CREDENTIALS_USR --password-stdin'
      }
    }
    stage('Push') {
      steps {
        sh 'docker push kannanb95/kaniyam:latest'
      }
    }
  }
  post {
    always {
      sh 'docker logout'
    }
  }
}

Enter fullscreen mode Exit fullscreen mode
  • Do the Git commit and push to the repo.

  • Login to Dockerhub >Account settings >Security >Access Token > Create New Access Token.

Image description

  • Go to Jenkins dashboard > Manage Jenkins >Credentials > systems > add docker hub credentials > at password tab paste the access token created on Docker hub.

Image description

  • At jenkins dashboard > Add items > named as "Dockerhub_jenkins" > Pipeline.

  • Pipeline > Definition > Pipeline script from SCM > set SCM as "Git"> Copy the Repo "URL" >Set branch as "Main" > save and apply > Build Now.

Image description

Image description

Image description

Image description

Image description

  • Verify the Dockerhub

Image description

Top comments (0)