Saturday , 4 Nov 2023

CI/CD NextJS application with github actions, pm2 and self-hosted runner

blog-page-image-nextjs-ci-cd

Setting up a CI/CD pipeline for a Next.js application using GitHub Actions, PM2, and deploying to a VDS (Virtual Dedicated Server) involves several steps. Below is a step-by-step guide:

Step 1: Prepare Your Next.js Application

Ensure that your Next.js application is version controlled with Git. Make sure your project has a `package.json` file and includes all the necessary dependencies.

Step 2: Install PM2 Locally

Install PM2 on your local machine using the following command:

npm install pm2 -g

Step 3: Configure PM2 for Your Next.js App

Navigate to your Next.js project directory and start your application with PM2:

cd /path/to/your/nextjs/app

pm2 start npm -- start

Ensure your Next.js app starts correctly using PM2.

Step 4: Create a GitHub Actions Workflow

In your Next.js project, create a directory .github/workflows if it doesn't exist. Inside that directory, create a YAML file, for example, ci-cd.yml, with the following content:

name: CI/CD Pipeline

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
    - name: Checkout Repository
      uses: actions/checkout@v2

    - name: Set up Node.js
      uses: actions/setup-node@v3
      with:
        node-version: 14

    - name: Install Dependencies
      run: npm install

    - name: Build and Test
      run: npm run build && npm run test

    - name: Deploy to VDS
      run: |
        # Add your deployment script here
        # Example: scp -r ./build/* user@your-vds-ip:/path/to/destination

    - name: Restart PM2 on VDS
      run: |
        # Add your PM2 restart script here
        # Example: ssh user@your-vds-ip "pm2 restart all"

Replace the deployment and PM2 restart script placeholders with your actual commands.

Step 5: Configure SSH Key for GitHub Actions

To enable GitHub Actions to deploy to your VDS, you need to add an SSH key to your GitHub repository. Follow the GitHub documentation on "Adding a new SSH key to your GitHub account".

Step 6: Update PM2 Configuration on Your VDS

Ensure that PM2 is installed on your VDS. You may need to install Node.js and NPM as well.

Step 7: Test the CI/CD Pipeline

Commit and push your changes to the main branch. Check the GitHub Actions tab on your repository to monitor the workflow's progress.

 

This guide provides a basic setup; you may need to customize it based on your specific project structure and requirements. Adjust the deployment steps, SSH key configuration, and PM2 commands according to your environment and preferences.

CI/CD
NextJS
GitHub Actions
PM2