在Docker容器中的mongodb副本集连接

时间:2018-05-14 18:00:13

标签: node.js docker mongoose containers replicaset

我在3个virtualbox vms,manasger1,worker1,worker2中创建了一个mongodb副本集。每个副本集都有自己的容器。副本集工作正常,我可以登录到服务器:

docker exec -it mongoNode1 bash -c 'mongo -u $MONGO_USER_ADMIN -p $MONGO_PASS_ADMIN --authenticationDatabase "admin"'
MongoDB shell version v3.6.4
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.4
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
    http://docs.mongodb.org/
Questions? Try the support group
    http://groups.google.com/group/mongodb-user
rs1:PRIMARY> use medmart_db
switched to db medmart_db
rs1:PRIMARY> db.providers.findObe()
2018-05-14T17:46:38.844+0000 E QUERY    [thread1] TypeError: db.providers.findObe is not a function :
@(shell):1:1
rs1:PRIMARY> db.providers.findOne()
{
    "_id" : ObjectId("56ddb50c230e405eafaf7781"),
    "provider_id" : 6829973073,

当我运行我的nodejs应用程序时,它连接到副本集。问题是,当我为我的应用程序创建一个容器时,我得到以下异常,我的容器停止,我不能再连接到副本集PRIMARY,而是连接到辅助节点。

(node:16) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [worker2:27017] on first connect [MongoNetworkError: connection 5 to worker2:27017 timed out]
     at Pool.<anonymous> (/home/nupp/app/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/server.js:505:11)
     at Pool.emit (events.js:182:13)
     at Connection.<anonymous> (/home/nupp/app/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:329:12)
     at Object.onceWrapper (events.js:273:13)
     at Connection.emit (events.js:182:13)
     at Socket.<anonymous> (/home/nupp/app/node_modules/mongoose/node_modules/mongodb-core/lib/connection/connection.js:256:10)
     at Object.onceWrapper (events.js:273:13)
     at Socket.emit (events.js:182:13)
     at Socket._onTimeout (net.js:447:8)
     at ontimeout (timers.js:427:11)
     at tryOnTimeout (timers.js:289:5)
     at listOnTimeout (timers.js:252:5)
     at Timer.processTimers (timers.js:212:10)
 (node:16) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
 (node:16) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我用mongoose打开了一张发行票,但他们的解决方案没有用(他们要求我从ip地址更改为域名,但我仍然得到同样的错误)。

我的连接模块是:

'use strict';
const mongoose = require('mongoose');
const getURL = (options) => {
    const url = options.servers.reduce((accumulator, current) => {
        accumulator += current+',';
        return accumulator;
    },`mongodb://${options.user}:${options.pass}@`);    
    return `${url.substr(0,url.length-1)}/${options.db}?replicaSet=${options.repl}&authSource=admin`;
}
const connect = (config, mediator) => {
    mediator.once('boot.ready', () => {
        const options = {
            native_parser: true,
            poolSize: 5,
            user: config.user,
            pass: config.pass,
            promiseLibrary: global.Promise,
            autoIndex: false, 
            reconnectTries: 30, 
            reconnectInterval: 500, 
            bufferMaxEntries: 0,
            connectWithNoPrimary: true ,
            readPreference: 'ReadPreference.SECONDARY_PREFERRED',
        };              
        mongoose.connect(getURL(config), options);
        mongoose.connection.on('error', (err) => {  
            mediator.emit('db.error', err);
        });
        mongoose.connection.on('connected', () => {
            mediator.emit('db.ready', mongoose);
        });
    });
};
module.exports = Object.assign({},{connect});

我的配置文件是:

'use strict';
const serverConfig = {
    port: 3000, 
};
const dbConfig = {
  db: 'xxxxxxx',
  user: 'xxxxxx',
  pass: 'xxxxxxx',
  repl: 'rs1',
  servers: (process.env.DB_SERVERS) ? process.env.DB_SERVERS.split(' ') : ['192.168.99.100:27017','192.168.99.101:27017','192.168.99.102:27017'],
};
module.exports = Object.assign({},{dbConfig, serverConfig});

1 个答案:

答案 0 :(得分:0)

因此,有几个步骤可以解决此问题。首先,必须更新virtualBox机器上的hosts文件以获得mongodb域的ip地址。要做到这一点:

> docker-machine ssh manager1
docker@manager1:~$ sudo vi /etc/hosts
#add the following
192.168.99.100 manager1
192.168.99.101 worker1
192.168.99.102 worker2

对worker1和worker2重复上述操作。 如果通过添加以下内容你很好,那么跳过第二部分。 接下来,如果您收到以下错误:

Error: ERROR::providers-service::model::ProviderModel::getProviderById: TypeError: Cannot read property 'wireProtocolHandler' of null
     at cb (/home/nupp/app/src/model/ProviderModel.js:182:13)
     at /home/nupp/app/node_modules/mongoose/lib/model.js:4161:16
     at Immediate.Query.base.findOne.call (/home/nupp/app/node_modules/mongoose/lib/query.js:1529:14)
     at Immediate.<anonymous> (/home/nupp/app/node_modules/mquery/lib/utils.js:119:16)
     at runCallback (timers.js:696:18)
     at tryOnImmediate (timers.js:667:5)
     at processImmediate (timers.js:649:5)

删除mongoose.connect的所有选项。以下是我的看法:

mediator.once('boot.ready', () => {
        const options = {};         
        mongoose.connect(getURL(config), options);
        mongoose.connection.on('error', (err) => {  
            mediator.emit('db.error', err);
        });
        mongoose.connection.on('connected', () => { 
            mediator.emit('db.ready', mongoose);
        });
    });

希望我的解决方案可以帮助其他人。花了我几天的时间才弄明白这一点。