Keep your apps running with PM2
A program you start by hand in an SSH session stops when the session ends. PM2 is a process manager: a tool that runs your app in the background, restarts it after a crash and starts it after a reboot. It works with any executable, not only Node.js apps.
What you need
- An open SSH connection to your container. If you have not connected yet, follow Connect to your VPS over SSH.
- Node.js and npm, because you install PM2 with npm. To install them, run
sudo apt install -y nodejs npm, as shown in Deploy a Node.js app on your VPS from scratch. - An app that you can start from the command line, for example with
node app.js.
Install and start your app
# install PM2 globally (needs sudo)
sudo npm install -g pm2
# start your app and name it myapp
pm2 start app.js --name myapp
# or: pm2 start npm -- startPM2 starts other programs too: pm2 start "python3 app.py" --name myapp for a Python script, or pm2 start ./myapp --name myapp for a compiled binary. The name after --name is how you refer to the app in later commands.
Start on boot
Create the startup command
Run
pm2 startup. It prints a command that starts withsudo.Run the command it printed
Copy that command and run it. This registers PM2 as a system service, so it starts when the container boots.
Save your app list
Run
pm2 save. PM2 now restarts every app on the list after a reboot.
Everyday commands
pm2 listshows all processes.pm2 logs myappshows the live logs.pm2 restart myapprestarts the app.pm2 stop myappstops the app but keeps it in the list.pm2 delete myappremoves the app from PM2.- After you start or delete an app, run
pm2 saveagain so that the list used at boot stays up to date.