App hosting

Keep a Node.js app running with PM2

On a Linux VPS, keep your app running after crashes and after the server restarts.

On App Hosting the panel keeps your app running for you. On a VPS or dedicated server you need a process manager. PM2 restarts the app if it stops, starts it again after a server reboot and keeps its logs.

  1. Install PM2

    bash
    npm install -g pm2
  2. Start the app

    Go to the app folder, install its dependencies and start it with a name:

    bash
    cd /home/my-app
    npm install
    pm2 start index.js --name my-app
  3. Start it automatically after a reboot

    bash
    pm2 startup

    The command prints a line that starts with sudo env PATH=.... Copy it and run it. Then save the list of running apps:

    bash
    pm2 save
  4. Check it

    bash
    pm2 status

    The app should be listed as online.

Useful commands

CommandWhat it does
pm2 logs my-appShows the logs live
pm2 restart my-appRestarts the app, for example after an update
pm2 stop my-appStops the app
pm2 delete my-appRemoves it from PM2
pm2 monitShows CPU and memory use