Breaking

Showing posts with label jenkins. Show all posts
Showing posts with label jenkins. Show all posts
January 13, 2024

Building a CI/CD pipeline for a Node.js app with Docker and Jenkins


So, you've got this fantastic Node.js app, and now you're thinking, "How can I make the development and deployment process smoother than a freshly paved road?" Well, my friend, the answer lies in creating a robust CI/CD pipeline using Docker and Jenkins. Buckle up, because we're about to embark on a journey of automation and efficiency!


Learn how to build a comprehensive CI/CD pipeline for your Node.js application using Docker and Jenkins. This guide provides step-by-step instructions


What's CI/CD, Anyway?

Before we dive in, let's quickly chat about CI/CD. CI stands for Continuous Integration, where code changes from multiple contributors are automatically merged into a shared repository. CD, on the other hand, expands to Continuous Delivery or Continuous Deployment, ensuring that your code is always in a deployable state.

Step 1: Setting Up Jenkins

First things first, let's get Jenkins up and running. Install Jenkins on your server, and don't forget to grab some coffee while you wait. Once Jenkins is installed, access the web interface and set up your pipelines. you can see the guide install jenkins

Articel related : Setup Jenkins on Kubernetes

Step 2: Dockerizing Your Node.js App

Time to containerize! Create a Dockerfile for your Node.js app, specifying the base image, dependencies, and commands to run your app. Docker makes your app independent of the environment, ensuring consistency across different stages of your pipeline.

Articel related : How to Setup Docker Containers as Build Agents for Jenkins

Create a Docker file for apps dockerized

FROM node:latest
WORKDIR /apps
ADD . .
RUN npm install
EXPOSE 3000
CMD ["node", "index.js"]


Here, I use my project  github link  :  node-dockerized-projects 




Step 3: Jenkins Pipeline Configuration

Now, let's tell Jenkins what to do. Create a Jenkinsfile in your project repository, defining the stages of your pipeline. This file will be your guiding light for Jenkins, ensuring it knows how to build, test, and deploy your app.

In a Jenkins pipeline, Groovy code is typically defined in a Jenkins file, which is a text file containing the pipeline definition. Jenkins files are written in the Groovy programming language and are used to define stages, phases, and other components of a process.

There are many stages checkout, test,build, build image, docker push to docker hub and docker run

1. Stage CheckOut

In a jenkins pipelines the checkout stage is stage use fetch form version control system (SCM).SCM. Here, i use Github as my version control system ( SCM).

In pipelines, in the agent section, you can specify the agent node. If you're using a remote Docker host to deploy a Node.js application, you can refer to the guide on adding a Docker agent in Jenkins. Like the slave-devopsgol

pipeline {
    agent {
           label 'slave-devopsgol'
    }
    stages{
        stage("checkout"){
            steps{
                checkout scm
            }
        }


2. Stage Test

In Jenkins pipelines, the testing stages include installing npm packages for requirements.

        stage("Test"){
            steps{
                sh 'sudo apt install npm -y'
                sh 'npm test'
            }
        }
3. Stage Build NPM 

In the build stage of NPM, it runs Node.js apps using the command npm run build.

        stage("Build NPM"){
            steps{
                sh 'npm run build'
            }
        }
4. Stage  Build Image 
In a Jenkins pipeline, the "Build" step is typically the first one, responsible for generating the source code.

The "Build" step can encompass all the necessary actions to compile the code, package it in a usable format, and perform other required preparation tasks.

        stage("Build Image"){
            steps{
                sh 'sudo docker build -t my-node-app:latest .'
            }
        }
5.  Stage Build  Push to docker hub

In the stages section, "Build push to docker hub" carries out the task of pushing the generated Docker image from the Build Image stage to Docker Hub.

        stage('Docker Build Push to DockerHub') {
            steps {
                withCredentials([usernamePassword(credentialsId: 'docker_cred', passwordVariable: 'DOCKERHUB_PASSWORD', usernameVariable: 'DOCKERHUB_USERNAME')]) {
                    sh 'sudo docker login -u $DOCKERHUB_USERNAME -p $DOCKERHUB_PASSWORD'
                    sh 'sudo docker tag my-node-app:latest adinugroho251/my-node-app:latest'
                    sh 'sudo docker push adinugroho251/my-node-app:latest'
                    sh 'sudo docker logout'
                }
            }
        }
6. Stage  Docker run

In the "docker run" stage, it runs the container that has been pushed to Docker Hub, using port 3000 as the exposed port according to the Dockerfile.

      stage('Docker RUN') {
          steps {
           sh 'sudo docker run -d -p 3000 --name deploy-apps-nodejs-devopsgol-test-successfully  adinugroho251/my-node-app:latest'
      }
    }

Complete Pipelines Jenkinsfile

Details for a jenkinsfile deploy application simple nodejs. Sure, I can certainly check out the source code on the GitHub link you provided : https://github.com/devopsgol/node-dockerized-projects.git

pipeline {
    agent {
           label 'slave-devopsgol'
    }
    stages{
        stage("checkout"){
            steps{
                checkout scm
            }
        }

        stage("Test"){
            steps{
                sh 'sudo apt install npm -y'
                sh 'npm test'
            }
        }

        stage("Build"){
            steps{
                sh 'npm run build'
            }
        }

        stage("Build Image"){
            steps{
                sh 'sudo docker build -t my-node-app:latest .'
            }
        }
        stage('Docker Push') {
            steps {
                withCredentials([usernamePassword(credentialsId: 'docker_cred', passwordVariable: 'DOCKERHUB_PASSWORD', usernameVariable: 'DOCKERHUB_USERNAME')]) {
                    sh 'sudo docker login -u $DOCKERHUB_USERNAME -p $DOCKERHUB_PASSWORD'
                    sh 'sudo docker tag my-node-app:latest adinugroho251/my-node-app:latest'
                    sh 'sudo docker push adinugroho251/my-node-app:latest'
                    sh 'sudo docker logout'
                }
            }
        }

      stage('Docker RUN') {
          steps {
           sh 'sudo docker run -d -p 3000 --name deploy-apps-nodejs-devopsgol  adinugroho251/my-node-app:latest'
      }
    }
}    
}
    

Step 4: Docker Registry Credentials

To push your Docker image to a registry, you'll need credentials. In Jenkins, go to "Manage Jenkins" > "Manage Credentials" > "Jenkins" > "Global credentials" and add your Docker Hub or any other registry credentials.

To push your Docker image to a registry, you'll need credentials.


Articel Related : HOW TO INTEGRATION OF SLACK NOTIFICATIONS WITH JENKINS

Step 5: Run Your Pipeline in jenkins

Once you've finished generating the Dockerfile and Jenkinsfile steps, now you can create job pipelines to execute that Jenkinsfile.

Create a job with the type "Pipeline."

Create a job with the type "Pipeline."

To enable auto-deployments, whenever a developer makes the last commits on GitHub, Jenkins will automatically trigger the build in the specified job.

To enable auto-deployments, whenever a developer makes the last commits on GitHub, Jenkins will automatically trigger the build in the specified job.
In the Pipelines section, input your GitHub project link and save the changes. Apply the settings afterward.

In the Pipelines section, input your GitHub project link and save the changes. Apply the settings afterward.
Click build now

Build Now
Alhamdulilah Sucessfully Deploy Application Node.js with docker using Jenkins


Well's running container for docker remote host and test curl port apps node.js is running well's

# docker ps  -a  | grep deploy-apps-nodejs-devopsgol-test-successfully
511915f0e75f   adinugroho251/my-node-app:latest              "docker-entrypoint.s…"   About a minute ago   Up About a minute   0.0.0.0:33052->3000/tcp, :::33052->3000/tcp                                            deploy-apps-nodejs-devopsgol-test-successfully
# curl  10.20.40.45:33052
Hello World!

Conslusion

It's showtime! Trigger your Jenkins pipeline and watch the magic happen. Jenkins will fetch your code, build, test, and deploy it in a seamless flow. Sit back and enjoy the automation symphony!

Congratulations, you've just built a CI/CD pipeline for your Node.js app using Docker and Jenkins. Now, every code change will go through this automated process, ensuring reliability and speed in your development lifecycle. Happy coding! 🚀

January 08, 2024

How to Setup Docker Containers as Build Agents for Jenkins

In the realm of DevOps, orchestrating seamless workflows is imperative, and Jenkins, with its extensibility, stands out as a powerhouse. 

In this comprehensive tutorial, we will delve into the integration of Docker and SSH for Jenkins agents, providing a step-by-step guide to enhance your CI/CD pipelines. You can see the previous guide, namely setup Jenkins on Kubernetes


Learn how to integrate Docker and SSH to set up a Jenkins agent for continuous integration and deployment (CI/CD) pipelines in this comprehensive tuto


Prerequisites 

Before embarking on this journey, ensure you have the following prerequisites in place:

 

  1.      A Jenkins server up and running.

 2.     Docker installed on both the Jenkins server and the machine you intend to use as a Docker host.

 3.     SSH access configured between the Jenkins server and the Docker host.

 4.    Java should be installed on your agent server.

 

Step 1: Set Up Jenkins


Open your Jenkins dashboard and navigate to "Manage Jenkins."

 

New code button in settings page. Access it through Jenkins dashboard by navigating to "Manage Jenkins."

Click on "Manage Nodes "


 

Settings page with new code button. Access additional options by clicking 'Manage Nodes'


Select "New Node" to create a new Jenkins agent.

 New code button in settings page. Click "New Node" to create a Jenkins agent.


Provide a name for the agent and choose "Permanent Agent."


'New code button in settings page: Name agent and select "Permanent Agent


In the configuration, specify the following:


New code button in settings page. Remote root directory: Choose directory for launching Jenkins agents.


•        Remote root directory: Choose a directory on the Docker host where Jenkins agents will be launched.

•        Labels: Assign labels to the agent for identification.


Related Article :  HOW TO INSTALL AND USE DOCKER : Getting Beginner


Select Manage Jenkins --> Credentials --> system --> Global unrestricted --> add credentials 


New code button in settings page. Accessible via Manage Jenkins --> Credentials --> system --> Global unrestricted --> add credentials.'


Input username and  password  for docker host. Example for user jenkins 



Input the ip addres of the  docker host




Note :

  • Usage : Select Usage this is node much as possible  for node ssh
  • Lauch Method : Select agent ssh for add node  docker with ssh agent
  • Host  :  Input IP ADDRESS OR Hostname Docker Host 
  • Credentials :   Select Credentials for docker host. 

 Save the configuration.

Related Articel :  How to Install Kubernetes on Ubuntu 20.04

Step 2 : Create user  jenkins  and install java for docker host


Add user jenkins in docker host

#  adduser jenkins


Add entri file  below this paragraph  in visudo

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL
jenkins ALL=(ALL) NOPASSWD: ALL
# See sudoers(5) for more information on "@include" directives:


Install package java for  requiretment jenkins agent 


# sudo apt install default-jre -y


Verify java version 


# java --version
openjdk 11.0.21 2023-10-17
OpenJDK Runtime Environment (build 11.0.21+9-post-Ubuntu-0ubuntu122.04)
OpenJDK 64-Bit Server VM (build 11.0.21+9-post-Ubuntu-0ubuntu122.04, mixed mode, sharing)


Step 3 :  Install Docker  Plugin

 

In the Jenkins dashboard, navigate to "Manage Jenkins" > "Manage Plugins." >> Select Plugins --> Install

New code button in settings page for installing Docker plugin using Jenkins

Select  Plugin this below : 

CloudBees Docker Build and Publish plugin Version 1.4.0

CloudBees Docker Custom Build Environment Plugin Version 1.7.3

CloudBees Docker Hub/Registry Notification Version 2.7.1

Docker


Step 4:  CI/CD : Automation Deploy Application HTML Using Jenkins

Fantastic! Adding a Docker node is a great step. Now, let's dive into deploying that simple HTML application via Jenkins. Here's a brief guide for you:

Prerequisites 

  1. Docker Hub 
  2. Jenkins Server is running 
  3. Dockerfile
  4. Jenkinsfile
Absolutely, adding Docker Hub credentials to Jenkins is a smart move for secure and seamless integration.

New code button in settings page for adding Docker Hub credentials.

Add  Credentials for docker hub 

New code button in settings page. Add Credentials for docker hub.

Example Dockerfile  


FROM nginx:latest
COPY ./html/. /usr/share/nginx/html/.
EXPOSE 80


Example Jenkinsfile 


pipeline {
    agent any
    stages{
        stage("checkout"){
            steps{
                checkout scm
            }
        }

        stage("Build Image"){
            steps{
                sh 'sudo docker build -t webserver-devopsgol-betahjomblo:1.0 .'
            }
        }
        stage('Docker Push') {
            steps {
                withCredentials([usernamePassword(credentialsId: 'docker_cred', passwordVariable: 'DOCKERHUB_PASSWORD', usernameVariable: 'DOCKERHUB_USERNAME')]) {
                    sh 'sudo docker login -u $DOCKERHUB_USERNAME -p $DOCKERHUB_PASSWORD'
                    sh 'sudo docker tag webserver-devopsgol-betahjomblo:1.0 adinugroho251/webserver-devopsgol-betahjomblo:1.0'
                    sh 'sudo docker push adinugroho251/webserver-devopsgol-betahjomblo:1.0'
                    sh 'sudo docker logout'
                }
            }
        }

      stage('Docker RUN') {
          steps {
           sh 'sudo docker run -d -p 80 --name webserver-betahjombloterus  adinugroho251/webserver-devopsgol-betahjomblo:1.0'
      }
    }
 }
}
    


For detail  projects simple html : https://github.com/devopsgol/apps-html


Add Job in Jenkins  for CI/CD 

Add Job in Jenkins


Select Restrict where this project can be run  for remote docker host  and input label docker agent ssh. 

Select Restrict where this project can be run  for remote docker host  and input label docker agent ssh.

Select Source code Manangement  and  input source code project. example for a github.
Source code Manangement

Checklist  Pool  SCM  for automation deploy using jenkins. When there's a code change from the Source Code Management (SCM) like GitHub or the latest commit changes, Jenkins will trigger to perform the build and deploy.


Pool  SCM  for automation deploy using jenkins. When there's a code change from the Source Code Management (SCM) like GitHub or the latest commit changes, Jenkins will trigger to perform the build and deploy.

Select  Build Steps --> Execute Shell 


Certainly! Here's the command to build the container:

imageName=web-devopsgol:${BUILD_NUMBER}
containerName=webserver-betahjombloterus 

sudo docker build -t $imageName .
sudo docker run -p 3000:3000 -d --name $containerName $imageName



Build Steps
Save Configuration  

Click Build Now  for running is job

Build now  is running job

Logs for job pipelines jenkins

Logs for job pipelines jenkins

Alhamdulilah container is running and successfuly curl in services application. 

Container is running well

Conlusion 

Congratulations! You have successfully integrated Docker and SSH for Jenkins agents, enhancing the scalability and flexibility of your CI/CD pipelines.

If you want to read more insightful tutorials and articles related to DevOps, feel free to visit The Insider's Views.