PM2 is a process manager for Node.js applications. It helps to monitor applications, their memory and CPU uses. Also, provides easy commands line to manipulate apps. In this article, I will explain to you how to deploy a Node.js application on a server using the
PM2 depends on Node.js and
python-software-properties, so we need to install them first:
sudo apt-get install python-software-properties curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash - sudo apt-get install nodejs
Then, we can install
sudo npm i -g pm2
PM2 provides a command line for users to generate a config file. The config file will be generated in the YAML format under the project folder.
pm2 ecosystem # generates a config file
After generation, there is a file like:
apps: - script : ./api.js name : 'api-app' instances: 4 exec_mode: cluster watch : true env : NODE_ENV: development env_production: NODE_ENV: production
Here are what some of the configuration options are for:
script: how to start the application. PM2 also supports starting Python applications.
instance: the number of instances you are going to create.
true, the application will auto-restart if any crash happened.
true, PM2 will restart the application if the application exceeds the amount of memory.
env: all the env variables settings should be placed here.
error_file: a path string for forwarding stderr
out_file: a path string for forwarding stdout
Now use the following command to start the application. PM2 will read the configuration file, start applications and assign a unique id to the process.
pm2 start config.yml
PM2 provides a list function for showing all applications under PM2:
If you need to get more detailed info about one specific app, we can use the command:
pm2 show [app_id]
Thanks for reading, and I hope you guys learned something!