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
tool.
Install PM2
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 pm2
globally:
sudo npm i -g pm2
Create the config file
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
Configuring PM2
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. -
exec_mode
:cluster
/fork
. -
watch
: iftrue
, the application will auto-restart if any crash happened. -
max_memory_restart
: iftrue
, 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
Start!
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:
pm2 list
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!
Top comments (4)
Wait a second. You didn't say anything about deploying the app 😄
He is actually talking about running the deployed app on the server 😋
start
anddeploy
are two different things in pm2, if you cd into your project and dopm2 ecosystem
you'll see the deploy portion at the end.He is talking about getting the local app to the server but in your post, you are assuming the project is on the server already...a better title will be
How I use PM2 to run Node.js applications to production.