I am trying to create node script cluster with PM2 but getting errors and its not working
Main node script in typescript
import express from 'express';
import mongoose from 'mongoose';
const app = express();
app.get('/', (req, res) => {
const tickets = {};
res.send(tickets);
});
const setup = async () => {
console.clear();
try {
await mongoose.connect('mongodb://127.0.0.1:27017/tickets', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
});
} catch(err) {
console.log(err);
}
app.listen(5001, () => {
console.log('listing app on 5001');
});
}
setup();
NPM run script
ts-node-dev --poll index.ts
My PM2 start script process.json
{
"apps" : [
{
"name" : "main-server",
"script" : "npm start",
"autorestart": true,
"instances" : 4,
"exec_mode" : "cluster"
}
]
}
and getting error
SyntaxError: Invalid or unexpected token
3|main-ser | at wrapSafe (internal/modules/cjs/loader.js:1047:16)
3|main-ser | at Module._compile (internal/modules/cjs/loader.js:1097:27)
3|main-ser | at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
3|main-ser | at Module.load (internal/modules/cjs/loader.js:977:32)
3|main-ser | at Function.Module._load (internal/modules/cjs/loader.js:877:14)
3|main-ser | at /usr/local/lib/node_modules/pm2/lib/ProcessContainer.js:303:25
3|main-ser | at wrapper (/usr/local/lib/node_modules/pm2/node_modules/async/internal/once.js:12:16)
3|main-ser | at next (/usr/local/lib/node_modules/pm2/node_modules/async/waterfall.js:96:20)
3|main-ser | at /usr/local/lib/node_modules/pm2/node_modules/async/internal/onlyOnce.js:12:16
3|main-ser | at WriteStream.<anonymous> (/usr/local/lib/node_modules/pm2/lib/Utility.js:186:13)
When i am running direct command with single instance "ts-node-dev --poll index.ts" its working fine running with once instance. but with PM2 cluster mode its not working and app not loading.
I think you have to call the main script file differently. Before a while I tried to get a process file running. After spending a lot of time, it worked for me somehow. Give it a try with this configuration:
{
"apps" : [
{
"name": "main-server",
"script": "./index.ts",
"node_args": [
"ts-node-dev",
"--poll"
],
"autorestart": true,
"instances": 4,
"exec_interpreter": "node",
"exec_mode": "cluster",
"env": {
"NODE_ENV": "development"
},
"env_production": {
"NODE_ENV": "production"
}
}
]
}
script
is calling a file, not the npm commandnode_args
exec_interpreter
is node
or the whole path e.g. /usr/bin/nodejs
env
is important.Run it in dev mode with pm2 start process.json
and in
prod mode with pm2 start process.json --env production
.
Not tested. Good luck.