Node.js WebApp Auto Deployment Using PM2 and GitHub Actions

Automating the deployment process for your Node.js web application can save you a significant amount of time and effort. By integrating PM2 with GitHub Actions, you can set up a continuous deployment pipeline that ensures your application is always up-to-date. This guide will walk you through the steps to set up your environment and create a seamless deployment workflow.

Step 1: Install Environment

1. Install Node.js and npm

Ensure you have Node.js and npm installed on your server. You can do this by downloading the installer from the official Node.js website or using a package manager.

2. Install Essential Tools

Install additional necessary tools like screen and vim. These tools are useful for managing terminal sessions and editing files, respectively.

3. Install PM2

PM2 is a process manager for Node.js applications. You can install it globally using npm:

1
sudo npm install -g pm2

4. Allow Non-Root User to Use Port 80 (optional)

To let a non-root user bind to port 80, you can use libcap2-bin. This step is optional but recommended for running your application on standard HTTP port:

1
2
apt install libcap2-bin -y
sudo setcap 'cap_net_bind_service=+ep' $(which node)

5. Create GitHub Self-Hosted Runner

Set up a self-hosted runner on GitHub by following the instructions in your repository settings under “Actions”. This runner will be responsible for executing your deployment pipeline.
follow repo-setting-action-self-host

6. Create GitHub Action Workflow: deploy.yml

Create a GitHub Actions workflow file in your repository under .github/workflows/deploy.yml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
name: Node.js CI

on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]

jobs:
build:

runs-on: [self-hosted, Production]

steps:
- uses: actions/checkout@v4
- name: Use Node.js 20.x
uses: actions/setup-node@v2
with:
node-version: 20.x
- run: npm install
- run: pm2 restart YOUR-WEBAPP-NAME

7. setup pm2 services

Start your Node.js application with PM2. For example, if your entry file is server.js:

1
pm2 start server.js --name YOUR-WEBAPP-NAME --time

Verify and Monitor Your Application

Check PM2 Status

Verify that your application is running properly with:

1
pm2 status

Check PM2 Logs

View your application’s logs:

1
pm2 logs

Real-Time Monitoring

Monitor your application’s performance and logs in real-time:

1
pm2 monit

Other Useful PM2 Commands

Manage your PM2 processes with these additional commands:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Delete a process by its id
pm2 del <id>

# Delete all processes
pm2 del all

# Start a specific process by name
pm2 start <name>

# Stop a specific process by name
pm2 stop <name>

# Configure PM2 to start on system startup
pm2 startup

# Save the process list to be loaded on startup
pm2 save

For more detailed information on PM2 features and usage, visit the PM2 Documentation.