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

Install and start your app

Install PM2 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 -- start

PM2 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

  1. Create the startup command

    Run pm2 startup. It prints a command that starts with sudo.

  2. 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.

  3. Save your app list

    Run pm2 save. PM2 now restarts every app on the list after a reboot.

Everyday commands

  • pm2 list shows all processes.
  • pm2 logs myapp shows the live logs.
  • pm2 restart myapp restarts the app.
  • pm2 stop myapp stops the app but keeps it in the list.
  • pm2 delete myapp removes the app from PM2.
  • After you start or delete an app, run pm2 save again so that the list used at boot stays up to date.

Follow along on your own container

Already have an account? Sign in to try this guide on your container. Accounts are created by invitation.

Sign in