I am trying to run my node.js application that uses socket.io on a linux ec2 instance using pm2 in cluster mode, when I run my application using pm2 start /var/www/html/backend/index.js
I am successfully able to create a connection with my server using socket.io-client library
const socket = io("http://myPublicIp:3001");
but when I try to run my server with pm2 start /var/www/html/backend/index.js -i max
I can no longer create a connection with my server.
after some research, I found out that I have to use @socket.io/redis-adapter library in my code but after 3 days of trying, I can't seem to get it to work.
any help would be appretiated
I have installed @socket.io/redis-adapter library and created the adapters. i have also registered the redis adapters to the io object as it was shown in the documentation here
here is my code from index.js
// importing Express server
const express = require("express");
const cors = require('cors');
// initializing our server
const app = express();
const {logger} = require("./config/pino.config");
const socket = require('socket.io');
const http = require('http');
const { createClient } = require("redis");
const { createAdapter } = require("@socket.io/redis-adapter");
// ...
// attaching routers and other modules to my express app
// ...
// listening on PORT or 3001
const PORT = process.env.SERVER_PORT || 3001;
// const server = app.listen(PORT, () => logger.info(`Listening on port ${PORT}`));
const server = http.createServer(app);
// socket.io
const io = socket(server, {
cors: {
origin: '*',
}
});
// const pubClient = createClient({ host: "localhost", port: 6379 });
const pubClient = createClient({url: 'redis://localhost:6379'});
const subClient = pubClient.duplicate();
// Promise.all([pubClient.connect(), subClient.connect()]).then(() => {
// io.adapter(createAdapter(pubClient, subClient));
// });
try {
Promise.all([pubClient.connect(), subClient.connect()]).then(() => {
io.adapter(createAdapter(pubClient, subClient));
});
} catch (err) {
console.error(err);
}
server.listen(PORT, () => logger.info(`Listening on port ${PORT}`));
io.on('connection', (socket, io) => {
connection(socket, io);
});
gameEvents.on('game_started', (game_id) => {
handleGameStartedEvent(game_id, io);
});
I don't get any errors when I run my app.
I have installed pm2 on my local machine (windows 11) and when I run pm2 start /var/www/html/backend/index.js -i max
it works fine.
also when I run that code using node index.js
or pm2 start /var/www/html/backend/index.js
it also works fine.
the problem is only when i attach -i max option to the pm2 command.