DEV Community

Jona
Jona

Posted on

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

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
Enter fullscreen mode Exit fullscreen mode

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

2. Setting up NestJS

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

npm install -D @nx/nest
npx nx g @nx/nest:app my-nest-app
Enter fullscreen mode Exit fullscreen mode

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

3.Running NestJS with PM2

Install PM2 globally.

npm install pm2 -g
Enter fullscreen mode Exit fullscreen mode

Install Nx-PM2-Plugin

npm i nx-pm2-plugin
Enter fullscreen mode Exit fullscreen mode

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"
    }
}
Enter fullscreen mode Exit fullscreen mode

You can now run the task using the following command:

npx nx run my-nest-app:pm2
Enter fullscreen mode Exit fullscreen mode

You can monitor the service instances using the following command:

pm2 monit
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)