Как подключить сервер MongoDB через туннель S SH с кластером NodeJS (несколько рабочих) - PullRequest
0 голосов
/ 01 мая 2020

Я использую cluster в моем NodeJS, чтобы максимизировать производительность.

Проблема возникает, когда я подключаюсь к MongoDB через S SH, первое соединение worker с сервером MongoDB через S SH успешен, но когда остальные worker, пытающиеся подключиться к MongoDB, столкнутся с ошибкой {"errno":"EADDRINUSE","code":"EADDRINUSE","syscall":"bind","address":"127.0.0.1","port":27017}, когда я считаю, что порт используется и предполагается, что он подключается только один раз.

Ниже мой код:

server.js

const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
const mongodb = require("./server/services/mongodb")
const express = require('express');
const app = express()
const https = require('https').createServer(serverOptions, app)
const http = require('http').createServer(app);


if (cluster.isMaster) {
    console.log(`Master ${process.pid} is running`);

    // Fork workers.
    for (let i = 0; i < numCPUs; i++) {
        let worker = cluster.fork();
    }

} else {
    console.log(`Worker ${process.pid} started`)
    // Workers can share any TCP connection
    // In this case it is an HTTP server
    //------------Turn on Web Server

    https.listen(webserverConfig.port, function () {
        console.log('listening on *:' + webserverConfig.port);
    })

    http.listen(80, function () {
        console.log('listening on *:80');
    });
}

mongodb.js

const tunnel = require("tunnel-ssh")
const mongo = require("mongodb")
const MongoClient = mongo.MongoClient;

var config = require("../config/config.js")
var dbConfig = new config.db(config.env)
var url = "mongodb://" + dbConfig.username + dbConfig.password + "localhost:27017/" + dbConfig.name;

var DB



var dbServer = tunnel(sshConfig, function (error, tnl) {
  if (error) {
    return console.log({ desc: 'configuration error on SSH connection :', error });
  }
  console.log("using SSH now")
  connect()
});
// Use a listener to handle errors outside the callback
dbServer.on('error', function (err) {
  console.log({ desc: 'Something bad happened on SSH connection :', err });
});


function connect() {
  MongoClient.connect(url, function (err, db) {
    if (err) {
      console.log(err)
    };
    db.on("close", () => {
      console.log("Mongodb connection closed")
      connect()
    })

    DB = db.db(config.name)
    console.log("MongoDB Succesfully connected to", dbConfig.name);
  });
}

Console Error

MongoDB Succesfully connected to _____
{"desc":"Something bad happened on SSH connection :","err":{"errno":"EADDRINUSE","code":"EADDRINUSE","syscall":"bind","address":"127.0.0.1","port":27017}}
{"desc":"Something bad happened on SSH connection :","err":{"errno":"EADDRINUSE","code":"EADDRINUSE","syscall":"bind","address":"127.0.0.1","port":27017}}
{"desc":"Something bad happened on SSH connection :","err":{"errno":"EADDRINUSE","code":"EADDRINUSE","syscall":"bind","address":"127.0.0.1","port":27017}}
{"desc":"Something bad happened on SSH connection :","err":{"errno":"EADDRINUSE","code":"EADDRINUSE","syscall":"bind","address":"127.0.0.1","port":27017}}
{"desc":"Something bad happened on SSH connection :","err":{"errno":"EADDRINUSE","code":"EADDRINUSE","syscall":"bind","address":"127.0.0.1","port":27017}}
{"desc":"Something bad happened on SSH connection :","err":{"errno":"EADDRINUSE","code":"EADDRINUSE","syscall":"bind","address":"127.0.0.1","port":27017}}
{"desc":"Something bad happened on SSH connection :","err":{"errno":"EADDRINUSE","code":"EADDRINUSE","syscall":"bind","address":"127.0.0.1","port":27017}}
{"desc":"Something bad happened on SSH connection :","err":{"errno":"EADDRINUSE","code":"EADDRINUSE","syscall":"bind","address":"127.0.0.1","port":27017}}

//(Appear 8 times due to 8 cores)

Работает нормально без кластер, пожалуйста, сообщите и спасибо заранее.

1 Ответ

0 голосов
/ 02 мая 2020

По какой-то причине imports нужно поместить внутрь блока else из cluster.master, тогда он будет работать.

server.js

if (cluster.isMaster) {
    console.log(`Master ${process.pid} is running`);

    // Fork workers.
    for (let i = 0; i < numCPUs; i++) {
        let worker = cluster.fork();
    }

} else {
    console.log(`Worker ${process.pid} started`)
    // Workers can share any TCP connection
    // In this case it is an HTTP server
    const cluster = require('cluster');
    const numCPUs = require('os').cpus().length;
    const mongodb = require("./server/services/mongodb")
    const express = require('express');
    const app = express()
    const https = require('https').createServer(serverOptions, app)
    const http = require('http').createServer(app);
    //------------Turn on Web Server

    https.listen(webserverConfig.port, function () {
        console.log('listening on *:' + webserverConfig.port);
    })

    http.listen(80, function () {
        console.log('listening on *:80');
    });
}
...