Automate Docker Builds and Pushes with Jenkins: A Step-by-Step Guide

Automate Docker Builds and Pushes with Jenkins: A Step-by-Step Guide

ยท

4 min read

Pre-requisites:

  1. Jenkins Master is up and running.

  2. Jenkins slave is set up with Docker installed.

  3. Docker and Docker Pipeline plugins are installed in Jenkins.

  4. Docker Hub account is set up at Docker Cloud.


Step 1: Validate Jenkins Docker Setup

Ensure Jenkins can run Docker builds by validating the following pre-requisites:

  • Jenkins is running.

  • Jenkins has Docker installed.

  • Docker and Docker Pipeline plugins are installed in Jenkins.


Step 2: Create Credentials for Docker Hub

  1. Go to Jenkins UI:

    • Open Jenkins in your web browser.
  2. Click on Credentials:

    • Navigate to Manage Jenkins > Manage Credentials.
  3. Click on Global credentials:

    • Click on the (global) domain.
  4. Click on Add Credentials:

    • Click on the Add Credentials button on the left menu.

  5. Create Docker Hub Credentials:

    • Set Kind to Username with password.

    • Enter your Docker Hub username and password.

    • Set ID to dockerhub.

    • Click OK to save.


Step 3: Create Maven3 Variable under Global Tool Configuration

  1. Go to Global Tool Configuration:

    • Navigate to Manage Jenkins > Global Tool Configuration.
  2. Add Maven Installation:

    • Under Maven, click on Add Maven.

    • Set the Name to Maven3.

    • Set Install automatically if Maven is not already installed.

    • Save the configuration.


Step 4: Create a Pipeline in Jenkins

  1. Create New Pipeline Job:

    • Go to Jenkins dashboard.

    • Click on New Item.

    • Enter a name for your pipeline job.

    • Select Pipeline and click OK.

  2. Configure Pipeline from SCM:

  3. Jenkinsfile Configuration:

    • Ensure your Jenkinsfile in the repository contains the following script
pipeline {
    environment {
        imagename = "your-dockerhub-username/your-Dockerhub-public-repo"
        dockerImage = ''
        containerName = 'my-container' #container name
        dockerHubCredentials = 'dockerhub' #name of the credentialid stored int he Jenkins console
    }

    agent any

    stages {
        stage('Checkout') {
            steps {
                checkout([$class: 'GitSCM', branches: [[name: '*/main']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: 'your-bitbucket-credentials-id', url: 'https://github.com/your-repo.git']]])
            }
        }

        stage('Build') {
            steps {
                script {
                    sh 'mvn -f pom.xml clean install'
                }
            }
        }

        stage('Building Image') {
            steps {
                script {
                    dockerImage = docker.build("${imagename}:${BUILD_NUMBER}", ".")
                }
            }
        }

        stage('Running Image') {
            steps {
                script {
                    sh "docker run --rm -d --name ${containerName} ${dockerImage.imageName()}"
                }
            }
        }

        stage('Stop and Remove Container') {
            steps {
                script {
                    sh "docker stop ${containerName} || true"
                    sh "docker rm ${containerName} || true"
                }
            }
        }

        stage('Deploy Image') {
            steps {
                script {
                    withCredentials([usernamePassword(credentialsId: dockerHubCredentials, usernameVariable: 'DOCKER_USERNAME', passwordVariable: 'DOCKER_PASSWORD')]) {
                        sh "docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWORD"
                        sh "docker push ${dockerImage.imageName()}"
                    }
                }
            }
        }
    }
}

Step 5: Build the Pipeline

  1. Run the Pipeline:

    • After creating the pipeline and adjusting the values, go to the pipeline job page.

    • Click on Build Now to start the pipeline.

  2. Monitor the Build:

    • You can monitor the build progress in the Build History and Console Output sections.

Result:

After the pipeline completes, your Docker image will be built and pushed to Docker Hub with the build number as the tag. You can verify this by logging into Docker Hub and checking your repository navyaani14/pubrepo.

Note: If you face "permissions denied" while trying to connect to /var/run/docker.sock,

you can resolve it by running the following command in the Jenkins Instance:

This command changes the permissions of the Docker socket, allowing all users to access it. However, be cautious with this approach, as it can expose your Docker daemon to security risks.

Conclusion:

By following these steps, you will have set up a Jenkins pipeline to automatically build a Docker image from your code, run tests, and push the image to Docker Hub. This automation simplifies your CI/CD process and ensures consistent, reliable Docker builds.

The example repository containing source code, Jenkinsfile, and Dockerfile is available at NavyaDeveloper/jenkins-git-dokerhub.

Did you find this article valuable?

Support NavyaDevops by becoming a sponsor. Any amount is appreciated!

ย