#
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",
}],
};
Make sure you replace [app name]
and [username]
with the appropriate values.
If you have more than one app, you can place more than one object in the apps
array.
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.
You can navigate to http://localhost:3000 as long as...
- you're using a virtual machine,
- are working from the host machine, and
- you have port 3000 forwarded
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...
- Push changes to the repository
- Log into the server
- Pull changes to the cloned (running) app
- Install missing dependencies
- Rebuild the app
- Reload the pm2 processes
You can automate steps 2-6 with continuous integration.