PM2 is a very handy tool to keep your node.js application online. Here's a list of commands that are essential for deployment.
pm2 start --name=web yarn --start
or pm2 start --name=web --interpreter=bash yarn -- start
Start your application using yarn start
with pm2
and assign a name web
to the application.
--name
is useful for multiple applications in the same server. For example, backend server and web applications.
--interpreter=bash
if your terminal should run with bash.
pm2 delete web
or pm2 delete all
Remove the process that is running the web
application, if you assign a name previously. Or otherwise, delete with process id is possible as well.
pm2 list
or pm2 status
Show list of running processes managed by pm2
.
pm2 logs
or pm2 logs web
Retrieve logs of running processes.
pm2 flush
Remove currently logged output in log files.
If you have multiple applications to manage, it is recommended to use pm2 config file to manage the config of each application.
In parent directory:
Run pm2 ecosystem
to create a config file, Ecosystem File.
A ecosystem.config.js
file will be generated.
Here's a sample config file I used for my side project.
module.exports = {
apps: [
{
name: 'web',
script: 'yarn',
args: 'start',
cwd: './myproject-web',
interpreter: 'bash',
instances: 1,
env_production: {
NODE_ENV: 'production',
PORT: 3000,
},
},
{
name: 'api',
script: 'yarn',
args: 'start',
cwd: './myproject-backend',
interpreter: 'bash',
instances: 1,
env_production: {
NODE_ENV: 'production',
PORT: 5000,
},
}
],
};
That's all! Hope it helps.
Cheers.