Build, Tag & Push Docker Image to Docker Hub using Jenkins Pipeline

🎯 Objective

  • Build a Docker image for a Node.js app using Jenkins

  • Tag the image dynamically with build number or commit ID

  • Push the image to Docker Hub

  • Automate everything via a Jenkins Pipeline


🧰 Tools Used


🪜 Step-by-Step Procedure


1️⃣ Fork the Repo (If not done already)

Go to 👉 https://github.com/suneelprojects/nodejs-project-docker.git
Click Fork and work on your copy.


2️⃣ Install Docker on EC2 (if not already installed)

sudo yum update -y
sudo amazon-linux-extras enable docker
sudo yum install docker -y
sudo service docker start
sudo usermod -aG docker ec2-user

🚨 Reboot instance or re-login after usermod.


3️⃣ Install Jenkins on EC2 (if not already installed)

(Skip if already installed. Let me know if you want installation steps again.)


4️⃣ Create Docker Hub Credentials in Jenkins

  • Go to Jenkins Dashboard → Manage Jenkins → Credentials → (global)

  • Add Username and Password for Docker Hub

  • ID: dockerhub


5️⃣ Create Jenkins Pipeline Job

  • Go to Jenkins → New Item → dockerhub-push-pipeline → Type: Pipeline

6️⃣ Use this Jenkins Pipeline Script

pipeline {
    agent any

    environment {
        DOCKER_HUB_CREDENTIALS = credentials('dockerhub')
        IMAGE_NAME = 'yourdockerhubusername/nodejs-app'
        TAG = "v${BUILD_NUMBER}"
    }

    stages {
        stage('Clone Repo') {
            steps {
                git 'https://github.com/<your-username>/nodejs-project-docker.git'
            }
        }

        stage('Build Docker Image') {
            steps {
                sh 'docker build -t $IMAGE_NAME:$TAG .'
            }
        }

        stage('Login to Docker Hub') {
            steps {
                sh "echo $DOCKER_HUB_CREDENTIALS_PSW | docker login -u $DOCKER_HUB_CREDENTIALS_USR --password-stdin"
            }
        }

        stage('Push Image to Docker Hub') {
            steps {
                sh 'docker push $IMAGE_NAME:$TAG'
            }
        }

        stage('Logout') {
            steps {
                sh 'docker logout'
            }
        }
    }
}

✅ Replace yourdockerhubusername with your actual Docker Hub username.
This pipeline will tag the image as v1, v2, etc., based on Jenkins build number.


🔎 Understanding the Flow (How it works – In-Depth)

StepWhat Happens
Clone RepoJenkins pulls your code from GitHub
Build Docker ImageDocker image is created using your Dockerfile
Tag with VersionImage is tagged like yourname/app:v1, v2, etc.
AuthenticateSecure login to Docker Hub via Jenkins credentials
Push to Docker HubImage is uploaded to your Docker Hub repository
LogoutDocker session is closed for security
1
Subscribe to my newsletter

Read articles from Suneel Kumar Kola directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Suneel Kumar Kola
Suneel Kumar Kola