What I Wanted to Do
Node.js apps kept stopping every time I disconnected from SSH on my VPS. I needed PM2 to keep them running in the background.
Install PM2
npm install -g pm2
If you’re using nvm, make sure you’re on the right Node.js version before installing globally.
Start Your App
pm2 start app.js
# or with a name
pm2 start app.js --name myapp
Using --name makes it easier to manage later.
Common Commands
# List all running processes
pm2 list
# View logs
pm2 logs
pm2 logs myapp
# Restart
pm2 restart myapp
# Stop
pm2 stop myapp
# Remove from PM2
pm2 delete myapp
pm2 list also shows CPU and memory usage at a glance.
Auto-Start After Server Reboot
pm2 startup
This outputs a command — copy and run it:
sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u ubuntu --hp /home/ubuntu
Then save the current process list:
pm2 save
Now PM2 and your registered apps will start automatically on reboot.
Managing Config with ecosystem.config.js
When running multiple apps or setting environment variables, a config file keeps things organized.
module.exports = {
apps: [{
name: 'myapp',
script: './app.js',
env: {
NODE_ENV: 'production',
PORT: 3000
},
error_file: './logs/err.log',
out_file: './logs/out.log'
}]
};
pm2 start ecosystem.config.js
Common Pitfalls
- If you use nvm, PM2 may fail to find the Node.js binary after
pm2 startup— add the correct PATH to the startup command to fix it - Forgetting
pm2 savemeans your process list is lost after a reboot - Logs pile up fast — install
pm2-logrotateto handle rotation automatically - When using nginx as a reverse proxy, make sure the PORT matches in both configs
- Don’t mix root and non-root users with PM2 startup — it references the home directory of the running user
Related Posts
- Manage Node.js Versions with nvm
- nginx Reverse Proxy Setup for Node.js Apps
- Managing Services with systemd
- How to Check and Kill Processes in Linux
- Setting Up Docker on a VPS
Recommended Cloud Hosting
Looking for reliable cloud infrastructure? Check out these developer-friendly services.
- Cherry Servers - High-performance VPS and dedicated servers
- Cloudways - Managed cloud hosting for developers