Run node app.js in a terminal, close the terminal, and the app stops. Hit an unexpected error and it crashes for good. PM2 fixes both problems, which is why it appears in most guides to deploying Node.js on your own server.
How it works
PM2 runs as a background daemon that watches your apps. When one crashes, PM2 restarts it, and it writes their output to log files under ~/.pm2/logs. In cluster mode it runs several instances of the app and spreads requests across them to use more than one CPU core.
Example: the essential commands
npm install -g pm2
pm2 start app.js --name shop
pm2 list
pm2 logs shop
pm2 restart shop
pm2 startup # needs root
pm2 save
Or with an ecosystem.config.js file:
module.exports = {
apps: [{
name: "shop",
script: "app.js",
instances: 2,
env: { NODE_ENV: "production" }
}]
};
Then start it with pm2 start ecosystem.config.js.
Tools people mix up
| Tool | Role |
|---|---|
| PM2 | Production process manager on a server you control |
| nodemon | Restarts on code changes during development |
| systemd | Linux’s system service manager; needs root |
| Passenger | App server that runs your app with the web server, driven by requests |
A classic problem is running two copies of the same app (one under PM2 and one started by hand) which ends in EADDRINUSE.
On ArabyHost
There’s no root access, so pm2 startup can’t work and PM2 won’t come back on its own after a server restart. The approach on AI/Developer plans: web apps run through Setup Node.js App, which uses Phusion Passenger, and background workers such as Discord bots are kept alive by a cron job. This one checks every minute and starts the bot if it isn’t running:
* * * * * /usr/bin/flock -n /home/USER/bot/.lock /path/to/node /home/USER/bot/index.js >> /home/USER/bot/bot.log 2>&1
Replace /path/to/node with the Node.js path from your app’s environment: which node shows it once the environment is activated. Details in the Discord bot guide.
FAQ
What's the difference between PM2 and nodemon?
nodemon is a development tool that restarts your app when files change. PM2 is for production: it keeps the app alive after crashes and manages logs and multiple instances.
Why does my app stop after a server reboot even with PM2?
PM2 itself has to start with the system. pm2 startup creates a system service, which requires root access, and pm2 save stores the list of apps to bring back.
Do I need PM2 on hosting that uses Passenger?
Usually not, because Passenger already runs and restarts web apps. PM2 is most useful on a server you manage yourself with full privileges.