CI/CD for Node.js Applications with GitHub Actions
Guide to Setting Up CI/CD for Node.js Applications with GitHub Actions
Continuous Integration and Continuous Deployment (CI/CD) is essential for modern software development. It ensures that changes to your application are automatically built, tested, and deployed without manual intervention. This guide walks you through setting up a CI/CD pipeline for a Node.js application using GitHub Actions. We'll provide an example workflow file and explain each step.
Prerequisites
Before setting up CI/CD, ensure the following:
You may refer to Node.js, React.js, and Next.js Deployment with Nginx Using PM2 on a comprehensive guide on how to setup everything you need to get your app running and deployed on a vps.
Creating the GitHub Actions Workflow File
Step 1: Create the Workflow File Navigate to your project and create the file .github/workflows/deploy.yml
ssh root@your-server-ip
mkdir -p .github/workflows
mkdir -p .github/workflows
vi .github/workflows/deploy.yml
Step 2: Add the Workflow Configuration Paste the following configuration into the deploy.yml file:
name: Deploy Node.js App
on:
push:
branches:
- deploy
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '20'
cache: 'npm'
- name: Install Dependencies
run: npm ci
- name: Build Application
run: npm run build
- name: Setup SSH
run: |
mkdir -p ~/.ssh
echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
ssh-keyscan -H ${{ secrets.HOST }} >> ~/.ssh/known_hosts
- name: Deploy to Server
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.HOST }}
username: ${{ secrets.USERNAME }}
key: ${{ secrets.SSH_PRIVATE_KEY }}
script: |
cd /var/www/your-app-directory
git pull origin deploy
npm ci
npm install sharp
npm run build
pm2 restart your-app-name
The workflow listens for changes pushed to the deploy branch. You can modify this to fit your branching strategy (for e.g staging).
Configuring SSH and Deploy Keys
To securely deploy your application, you need to set up SSH keys and configure a deploy key for your server.
Step 1: Generate an SSH Key Pair
Run the following command on your local machine to generate a new SSH key pair:
ssh-keygen -t rsa -b 4096 -C "your-email@example.com"
Step 2: Copy the Public Key to Your Server
Step 3: Add the Private Key to GitHub Secrets
Step 5: Configure Deploy Keys
Set Up Secrets in GitHub
Testing Your Workflow
Step 1: Push Changes Push your changes to the deploy branch:
git add .
git commit -m "Test CI/CD pipeline"
git push origin deploy
** Step 2: Monitor Workflow Execution **