If you start a Node.js app with node server.js it stops the moment you close SSH or the app crashes. PM2 is a process manager that keeps apps running, restarts them automatically and starts them again after a reboot. This guide covers the PM2 commands you will use every day.
Before you start
- Node.js installed on your VPS. See Install Node.js and npm on a Linux VPS.
- An app that starts with a command such as
node server.jsornpm start. - A non-root user that owns the app files (recommended).
Note: On cPanel hosting you do not need PM2: Setup Node.js App uses Passenger to start and restart your app. See Set up a Node.js app in cPanel.
Install PM2
npm install -g pm2If you installed Node.js from NodeSource, prefix the command with sudo. With nvm, run it as the app user without sudo.
Start, stop and restart apps
- Start a plain script and give it a name:
pm2 start server.js --name api - Start an npm script, for example a Next.js app:
pm2 start npm --name web -- start - See what is running:
pm2 list - Restart, stop or remove an app:
pm2 restart api pm2 stop api pm2 delete api
pm2 reload api restarts with zero downtime when the app runs in cluster mode.
Use an ecosystem file
An ecosystem file keeps all settings in your project so every restart uses the same options. Create ecosystem.config.js in the project folder:
module.exports = {
apps: [{
name: 'web',
script: 'npm',
args: 'start',
cwd: '/home/deploy/myapp',
instances: 1,
max_memory_restart: '500M',
env: {
NODE_ENV: 'production',
PORT: 3000
}
}]
};Start it with:
pm2 start ecosystem.config.jsStart apps automatically at boot
- Generate the startup script:
pm2 startup systemd - PM2 prints a command beginning with
sudo env PATH=.... Copy and run it exactly as shown. - Save the current process list so it is restored at boot:
pm2 save
Run pm2 save again every time you add or remove an app.
Cluster mode
Node.js uses one CPU core per process. Cluster mode starts several copies behind one port:
pm2 start server.js --name api -i maxUse -i 2 for two instances. Apps that keep sessions or WebSocket state in memory need a shared store such as Redis before you scale out.
Logs and monitoring
pm2 logs api --lines 100
pm2 monitLogs are stored in ~/.pm2/logs. Install log rotation so they do not fill the disk:
pm2 install pm2-logrotate
pm2 set pm2-logrotate:max_size 20M
pm2 set pm2-logrotate:retain 7Troubleshooting
- App shows
erroredor keeps restarting — runpm2 logs NAME --errto see the crash message. - Apps missing after reboot — you skipped
pm2 saveor ranpm2 startupas a different user. - Wrong Node.js version — after switching versions with nvm, run
pm2 updateand restart apps.
