Published on

Guide to Running a Node Server in Nx Monorepo using PM2 Process Manager

Authors

Introduction

PM2 is a daemon process manager that will help you manage and keep your application online 24/7. It has a lot of features that will help you in the process of deploying and maintaining your application.

Additionally PM2 allows you to run a nodeJS server in cluster mode. Which dramatically improves the performance of your application and allows you to scale your application horizontally.

In this article we will cover the following:

  1. Setting up a Nx monorepo
  2. Setting up a NestJS project within the Nx Monorepo.
  3. Running NestJS with PM2 using Nx-PM2-Plugin.

It must be noted that the same approach can be used for any nodeJS project within Nx.

1. Setting up a Nx Monorepo

In this section we will be setting up a Nx monorepo using the integrated mode scheme.

npx create-nx-workspace@latest myorg --preset=ts

A comprehensive guide to setting up the Nx monorepo can be found here;

2. Setting up NestJS

Nx provides a NestJS generator to setup a NestJS project within the monorepo.

First install the NestJS generator.

npm install -D @nx/nest

Then generate a NestJS project.

npx nx g @nx/nest:app my-nest-app

A comprehensive guide to setup NestJS within Nx can be found here

3.Running NestJS with PM2

Install PM2 globally.

npm install pm2 -g

Install Nx-PM2-Plugin

npm i nx-pm2-plugin

Add the following task to project.json of the NestJS project.

"pm2": {
	"executor": "nx-pm2-plugin:pm2-executor",
	"options": {
		"command": "my-nest-app:serve:production",
		"name": "example"
	}
}

You can now run the task using the following command:

npx nx run my-nest-app:pm2

You can monitor the service instances using the following command:

pm2 monit

Conclusion

PM2 is a daemon process manager that will help you manage and keep your application online 24/7. It has a lot of features that will help you in the process of deploying and maintaining your application.