Run Node.js in production

Node.js is a great technology allowing flexibility and speed for building server side applications using javascript.
Once in the server, the command node path/to/app/main.js seems not to be the best solution, as important features like threading, caching, logging, or enhanced security are left behind, at the Node.js side.

In order to properly run a Node.js in production there exist many solutions out there.
A simple and effective one is to use the pm2 tool.

See notes on pm2 install in ther quick-start guide, and visit this post to have a glance on how to use Nginx as a backproxy for Node.js

In order to start the node application with pm2, run:

1
pm2 start path/to/app/main.js

It will start the application, store information about the process and provide commands for easy access to logs.

1
2
pm2 monit     # for complete overview
pm2 logs -f # for a tail mode logger

In order to list processes, simply:

1
pm2 ls

Output:
pm2 ls output

Cluster mode

In order to run a Node.js application in cluster mode, the application must be completely stateless, so the application instances can behave independently from each other.

Pm2 provides a good way to run applications in cluster mode. For that, define the processes unsing an ecosystem file. This file can be written in js, json or yaml. This example, processes.yml is written in yaml:

1
2
3
4
5
6
7
8
9
apps:
- script: ./path/to/app/app.js
name: 'app'
instances: 2
exec_mode: cluster
- script: ./path/to/app/server.js
name: 'server'
instances: 3
exec_mode: cluster

To execute run:

1
pm2 start path/to/processes.yml

Read more on how to define the ecosystem file in the pm2 docs