Cluster and Scale Node.js app with pm2

Farid Vosoughi
1 min readSep 9, 2022

--

In this article we want to increase Node.js application performance for handling heavy load traffic

When we run Node.js application, we assign one cpu thread for that. With pm2 you can cluster Node.js application to run more than one thread instance.

PM2 is a runtime process management and monitoring tool with a built-in load balancer for Node.js applications.
you can install it as globally or locally but for production container base application you can install it in Dockerfile.

FROM node:16-alpine

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . /app

# Install bash
RUN apk add --no-cache bash

RUN npm install -g pm2
RUN npm run build

#CMD ["node", "dist/src/main.js"]
CMD ["pm2-runtime", "start", "ecosystem.config.js"]
EXPOSE 3000

After dockerize your application, you should add ecosystem.config.js file in root of project.

module.exports = {
apps: [
{
name: `base-api-${process.env.NODE_ENV || 'env'}-worker`,
script: './dist/src/main.js',
instances: 1,
exec_mode: 'cluster',
autorestart: true,
},
],

In ecosystem.config.js in script section you can put main initiate js file like main.js or app.js. Instance section is for define number of app instances.

With pm2 start ecosystem.config.js we can run our clustering :)

--

--

Farid Vosoughi
Farid Vosoughi

Written by Farid Vosoughi

Interested in learning new technologies related to software development

No responses yet