# Manage Node.js Processes with PM2

# Prerequisites

  • A Node.js app (Next.js or otherwise) is servable
  • The Node.js app is not currently running
  • If using a virtual machine, port 3000 is forwarded

# Setup

Install PM2 globally using npm.

sudo npm install -g pm2

Create the file ~/apps/ecosystem.config.js.

module.exports = {
  apps: [{
    name: "[app name]",
    cwd: "/home/[username]/apps/[app name]",
    script: "node_modules/next/dist/bin/next",
    args: "start",
    instances: "max",
    exec_mode: "cluster",
    max_restarts: 5,
    log_date_format: "YYYY-MM-DDTHH:mmZ",
  }],
};

Start the process(es) using PM2.

pm2 start ~/apps/ecosystem.config.js

Open a web browser and navigate to http://[your server's IP address/hostname]:3000. You should see your Next.js app.

Save the currently running configuration.

pm2 save

View the startup script command.

pm2 startup

That command will output a command that looks something like this:

sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u myuser --hp /home/myuser

Copy the command.

Paste it into your terminal and press Enter to run it.

PM2 will now automatically start the saved Node.js processes at system startup. Try restarting the machine to test it.

Right now, the process for updating the app is...

  1. Push changes to the repository
  2. Log into the server
  3. Pull changes to the cloned (running) app
  4. Install missing dependencies
  5. Rebuild the app
  6. Reload the pm2 processes

You can automate steps 2-6 with continuous integration.