Day 27 Task: Jenkins Declarative Pipeline with Docker

🔹Create Declarative Pipeline with Docker

  1. From the Jenkins dashboard, click on "New Item" to create a new project.

  2. Enter a project name and select "Pipeline" Click "OK" to create the project.

  3. Under Source Code Management, select Git and Added the repository URL (my forked repository).

  4. Enabled GitHub hook trigger for GITScm polling.

GitHub WebHooks Setup:

  1. Accessed my repository on GitHub.

  2. Went to "Settings" > "Webhooks".

  3. Added a new webhook with my Jenkins job's URL Selected events to trigger (e.g., push, pull request).

  4. Saved the webhook.

Create Environment variable credential for docker hub:

  1. Click on "manage jenkins" > Credentials.

  2. Click on "Systum" > "Global Credentials(unrestricted)" > "Add Credentials".

Running the Application:

  1. Add the current user to the docker group:

     sudo usermod -aG docker $USER
     sudo reboot
    
  2. Add the Jenkins user to the docker group:

     sudo usermod -aG docker jenkins
     sudo systemctl restart jenkins
    
  3. Inside the Dashboard "todo-app" job > Within the Jenkins job's Pipeline build step.

     pipeline {
         agent any
    
         stages{
             stage('Clone Code'){
                 steps {
                     echo "Cloning the code"
                     git url:"https://github.com/GOPALGTM/node-todo-app.git", branch:"main"
                 }
             }
             stage('Build'){
                 steps {
                     echo "Building the Image"
                     sh "docker build -t todo-app ."
                 }
             }
             stage('push to dockerhub'){
                 steps {
                     echo "Pushing the code to dockerhub"
                     withCredentials([usernamePassword(credentialsId:"dockerhub",passwordVariable:"dockerHubPass",usernameVariable:"dockerHubUser")]){
                     sh "docker tag todo-app ${env.dockerHubUser}/node-app:latest"
                     sh "docker login -u ${env.dockerHubUser} -p ${env.dockerHubPass}"
                     sh "docker push ${env.dockerHubUser}/node-app:latest"
                     }
                 }
             }
             stage('Deploy'){
                 steps {
                     echo "Deploying the application"
                     sh "docker-compose down"
                     sh "docker-compose up -d --build"
    
                 }
             }
         }
     }
    

  4. Save and click on Build Now.