Managing Node.js Apps on VPS with PM2
PM2 (Process Manager 2) is a production-grade process manager for Node.js that keeps your application running continuously. It automatically restarts your app if it crashes, manages multiple worker processes to utilize all CPU cores, rotates logs automatically, and runs startup scripts on system boot. It's an essential tool for every Node.js server.
Installing PM2
# Install Node.js first (if not already installed)
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
# Install PM2 globally
sudo npm install -g pm2
# Check version
pm2 --version
Running Applications with PM2
# Start an application
pm2 start app.js --name "my-app"
# Run Next.js / specify an interpreter
pm2 start npm --name "nextjs-app" -- start
# Run in cluster mode (use all CPU cores)
pm2 start app.js -i max --name "my-app"
# View status
pm2 status
pm2 list
ecosystem.config.js (Recommended for Production)
nano ecosystem.config.js
module.exports = {
apps: [{
name: 'my-app',
script: 'app.js',
instances: 'max', // Use all CPU cores
exec_mode: 'cluster',
env: {
NODE_ENV: 'development',
PORT: 3000
},
env_production: {
NODE_ENV: 'production',
PORT: 3000
},
log_date_format: 'YYYY-MM-DD HH:mm:ss',
error_file: '/var/log/pm2/my-app-error.log',
out_file: '/var/log/pm2/my-app-out.log',
max_memory_restart: '512M' // Restart if memory exceeds limit
}]
}
# Run in production
pm2 start ecosystem.config.js --env production
Auto-start After Reboot
# Generate startup script
pm2 startup
# PM2 will display a command to run, for example:
# sudo env PATH=$PATH:/usr/bin pm2 startup systemd -u ubuntu --hp /home/ubuntu
# Save the current process list
pm2 save
pm2 save every time you add or remove processes to ensure PM2 remembers the list and restores it after a reboot.
Verify PM2 is Working Correctly
# View status of all processes
pm2 status
# View real-time logs
pm2 logs my-app --lines 50
# View CPU/RAM metrics
pm2 monit
# View detailed process information
pm2 show my-app
# Check if startup is saved
pm2 list # You should see online status
pm2 monit displays real-time CPU, RAM, and logs all on one screen, similar to htop but specifically for Node.js processes.
Common Issues & Troubleshooting
PM2 Process Status is "errored" or "stopped"
The app crashes immediately upon startup. Check the error log to find the cause:
# View error logs
pm2 logs my-app --err --lines 100
# Test by running Node directly first
node app.js
# Restart and watch logs
pm2 restart my-app && pm2 logs my-app
Port Conflicts with Multiple Processes
In cluster mode, all workers share the same port; PM2 handles round-robin distribution automatically. However, you must avoid hardcoding different ports per process:
# Use process.env.PORT in app.js
const PORT = process.env.PORT || 3000
app.listen(PORT)
PM2 Disappears After Reboot Despite Running pm2 startup
You forgot to run pm2 save after startup, or the Node.js path in the startup script is incorrect:
# Check systemd service status
systemctl status pm2-ubuntu
# If the service isn't active, regenerate the startup script
pm2 unstartup
pm2 startup
# Run the command that PM2 displays
pm2 save
Large Log Files Consuming Disk Space
Set up log rotation using the pm2-logrotate module:
pm2 install pm2-logrotate
pm2 set pm2-logrotate:max_size 50M
pm2 set pm2-logrotate:retain 7
pm2 set pm2-logrotate:compress true
Frequently Asked Questions
What's the difference between PM2 cluster mode and single mode?
Single mode runs one process on a single CPU core. Cluster mode runs N processes (where N equals the number of CPU cores), with each process being an independent Node.js instance that shares the TCP port through PM2's load balancer. This enables you to use multiple CPU cores (Node.js is normally single-threaded), dramatically increasing throughput.
How is PM2 different from systemd services?
PM2 is purpose-built for Node.js with features like clustering, log rotation, monitoring, and hot reloading. Systemd is a general-purpose init system that the OS uses to manage all services. PM2 actually creates a systemd service during the pm2 startup process. The two work together rather than replacing each other.
Can I deploy a new app version with zero downtime?
Yes, use pm2 reload my-app. PM2 reloads processes one at a time in a rolling update fashion within cluster mode, resulting in zero downtime. This is different from pm2 restart, which stops all processes and starts them all again simultaneously.