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 | apt install libcap2-bin -y |
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 | name: Node.js CI |
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 | # Delete a process by its id |
For more detailed information on PM2 features and usage, visit the PM2 Documentation.