PM2 is a battle-tested process manager for Node.js applications that provides automatic restarts, logging, monitoring, and cluster mode. This guide deploys a Node.js application in production using PM2 on Ubuntu 24.04 LTS.
Tested and valid on:
- Ubuntu 24.04 LTS
Prerequisites
- Ubuntu 24.04 LTS server
- Node.js 20 LTS installed
- Nginx installed (for reverse proxy)
Step 1 – Install PM2 Globally
Install PM2 via npm:
sudo npm install -g pm2
Step 2 – Create a Sample Node.js Application
Create a simple Express app:
mkdir /var/www/myapp && cd /var/www/myapp
npm init -y
npm install express
Create app.js:
const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello from Node.js on Ubuntu 24.04!'));
app.listen(3000, () => console.log('Server running on port 3000'));
Step 3 – Start the Application with PM2
Launch the application:
cd /var/www/myapp
pm2 start app.js --name myapp
Step 4 – Enable PM2 on System Boot
Generate and apply the startup command:
pm2 startup
# Copy and run the command PM2 outputs, e.g.:
# sudo env PATH=$PATH:/usr/bin pm2 startup systemd -u ubuntu --hp /home/ubuntu
pm2 save
Step 5 – Configure Nginx as a Reverse Proxy
Create an Nginx server block:
sudo nano /etc/nginx/sites-available/myapp
Add:
server {
listen 80;
server_name myapp.example.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
Enable and reload:
sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
Step 6 – Monitor with PM2
Useful PM2 commands:
pm2 list # list all processes
pm2 logs myapp # view logs
pm2 monit # real-time monitor
pm2 restart myapp # restart app
pm2 stop myapp # stop app
pm2 delete myapp # remove from PM2
Step 7 – Scale with Cluster Mode
Take advantage of all CPU cores:
pm2 restart myapp -i max # auto-detect CPU count
Conclusion
Your Node.js application is now running in production on Ubuntu 24.04 LTS with PM2 and Nginx. PM2 will automatically restart the application on crashes and system reboots.