In modern software development, continuous integration and continuous deployment (CI/CD) are essential practices that help teams deliver code efficiently and reliably. This tutorial guides you through setting up a CI/CD pipeline for a NestJS application using Jenkins, a popular automation server.

Prerequisites

  • Node.js and npm installed on your machine
  • Docker installed for containerization
  • Jenkins server set up and running
  • Basic knowledge of NestJS and Jenkins
  • Git repository hosting your NestJS project

Step 1: Prepare Your NestJS Application

Ensure your NestJS project is configured for production. Create a Dockerfile in your project root:

FROM node:14-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["node", "dist/main"]

Update your package.json scripts to include:

"scripts": {
  "build": "nest build",
  "start": "node dist/main"
}

Step 2: Set Up Jenkins Pipeline

In Jenkins, create a new pipeline job. Use the following pipeline script to automate build, test, and deployment:

pipeline {
  agent any
  environment {
    IMAGE_NAME = 'your-dockerhub-username/nestjs-app'
  }
  stages {
    stage('Checkout') {
      steps {
        git 'https://your-repo-url.git'
      }
    }
    stage('Install Dependencies') {
      steps {
        sh 'npm install'
      }
    }
    stage('Build') {
      steps {
        sh 'npm run build'
      }
    }
    stage('Test') {
      steps {
        sh 'npm test'
      }
    }
    stage('Build Docker Image') {
      steps {
        sh 'docker build -t $IMAGE_NAME:latest .'
      }
    }
    stage('Push Docker Image') {
      steps {
        withCredentials([usernamePassword(credentialsId: 'dockerhub-credentials', usernameVariable: 'DOCKER_USERNAME', passwordVariable: 'DOCKER_PASSWORD')]) {
          sh 'echo $DOCKER_PASSWORD | docker login -u $DOCKER_USERNAME --password-stdin'
          sh 'docker push $IMAGE_NAME:latest'
        }
      }
    }
    stage('Deploy') {
      steps {
        sh 'docker run -d -p 80:3000 --name nestjs_app $IMAGE_NAME:latest'
      }
    }
  }
  post {
    always {
      cleanWs()
    }
  }
}

Step 3: Configure Jenkins Credentials

Add your Docker Hub credentials in Jenkins under "Manage Jenkins" > "Manage Credentials". Use these credentials in your pipeline for authentication.

Step 4: Automate with Webhooks

Set up webhooks in your Git repository to trigger Jenkins builds on code pushes. This ensures your pipeline runs automatically whenever you update your code.

Conclusion

With these steps, you have established a CI/CD pipeline for your NestJS application using Jenkins. This setup automates building, testing, containerizing, and deploying your app, enabling faster and more reliable releases.