使用Docker容器中的MongoDB的副本集连接到Node.js应用

时间:2018-08-24 17:41:16

标签: node.js mongodb docker docker-compose replicaset

所以,是的。

我有这些容器运行的mongod,并且所有三个容器都使用docker-compose进行了如下配置:

    version: '3.5'
 services: 
  mongodb-primary:
   container_name: mongodb-primary
   depends_on:                            
     - mongodb-secondary
     - mongodb-arbiter
   image: mongo
   ports:
   - "30001:27017"
networks:                              
  - mongo-cluster
command: "mongod --replSet mongo-rs"

另一个和仲裁者相同,然后我得到了这个setup.sh

     mongo-setup:
container_name: mongo-setup
image: mongo
depends_on:
  - mongodb-primary
  - mongodb-secondary
  - mongodb-arbiter
volumes:
  - ./scripts/mongosetup.sh:/scripts/mongosetup.sh      
networks:
  - mongo-cluster
command: "bash /scripts/mongosetup.sh"

,然后当然是网络配置。

现在,使用:docker exec -it mongodb-secondary mongo -eval "rs.status()"

我明白了:

    MongoDB shell version v4.0.0
    connecting to: mongodb://127.0.0.1:27017
    MongoDB server version: 4.0.0
    {
    "set" : "mongo-rs",
    "date" : ISODate("2018-08-24T17:28:25.422Z"),
    "myState" : 2,
    "term" : NumberLong(12),
    "syncingTo" : "mongodb-primary:27017",
    "syncSourceHost" : "mongodb-primary:27017",
    "syncSourceId" : 0,
    "heartbeatIntervalMillis" : NumberLong(2000),
    "optimes" : {
            "lastCommittedOpTime" : {
                    "ts" : Timestamp(1535131703, 
     1),
                    "t" : NumberLong(12)
            },
            "readConcernMajorityOpTime" : {
                    "ts" : Timestamp(1535131703, 
     1),
                    "t" : NumberLong(12)
            },
            "appliedOpTime" : {
                    "ts" : Timestamp(1535131703, 
     1),
                    "t" : NumberLong(12)
            },
            "durableOpTime" : {
                    "ts" : Timestamp(1535131703, 
     1),
                    "t" : NumberLong(12)
            }
     },
     "lastStableCheckpointTimestamp" : 
     Timestamp(1535131683, 1),
         "members" : [
            {
                    "_id" : 0,
                    "name" : "mongodb- 
      primary:27017",
                    "health" : 1,
                    "state" : 1,
                    "stateStr" : "PRIMARY",
                    "uptime" : 2050,
                    "optime" : {
                            "ts" : 
         Timestamp(1535131703, 1),
                            "t" : NumberLong(12)
                    },
                    "optimeDurable" : {
                            "ts" : 
         Timestamp(1535131703, 1),
                            "t" : NumberLong(12)
                    },
                    "optimeDate" : ISODate("2018- 
         08-24T17:28:23Z"),
                    "optimeDurableDate" : 
         ISODate("2018-08-24T17:28:23Z"),
                    "lastHeartbeat" : 
         ISODate("2018-08-24T17:28:25.095Z"),
                    "lastHeartbeatRecv" : 
         ISODate("2018-08-24T17:28:24.433Z"),
                    "pingMs" : NumberLong(0),
                    "lastHeartbeatMessage" : "",
                    "syncingTo" : "",
                    "syncSourceHost" : "",
                    "syncSourceId" : -1,
                    "infoMessage" : "",
                    "electionTime" : 
        Timestamp(1535129672, 1),
                    "electionDate" : 
        ISODate("2018-08-24T16:54:32Z"),
                    "configVersion" : 1
            },
            {
                    "_id" : 1,
                    "name" : "mongodb- 
         secondary:27017",
                    "health" : 1,
                    "state" : 2,
                    "stateStr" : "SECONDARY",
                    "uptime" : 2055,
                    "optime" : {
                            "ts" : 
        Timestamp(1535131703, 1),
                            "t" : NumberLong(12)
                    },
                    "optimeDate" : ISODate("2018- 
        08-24T17:28:23Z"),
                    "syncingTo" : "mongodb- 
        primary:27017",
                    "syncSourceHost" : "mongodb- 
        primary:27017",
                    "syncSourceId" : 0,
                    "infoMessage" : "",
                    "configVersion" : 1,
                    "self" : true,
                    "lastHeartbeatMessage" : ""
            },
            {
                    "_id" : 2,
                    "name" : "mongodb- 
        arbiter:27017",
                    "health" : 1,
                    "state" : 7,
                    "stateStr" : "ARBITER",
                    "uptime" : 2052,
                    "lastHeartbeat" : 
           ISODate("2018-08-24T17:28:25.095Z"),
                    "lastHeartbeatRecv" : 
           ISODate("2018-08-24T17:28:24.158Z"),
                    "pingMs" : NumberLong(0),
                    "lastHeartbeatMessage" : "",
                    "syncingTo" : "",
                    "syncSourceHost" : "",
                    "syncSourceId" : -1,
                    "infoMessage" : "",
                    "configVersion" : 1
            }
    ],
    "ok" : 1,
    "operationTime" : Timestamp(1535131703, 1),
    "$clusterTime" : {
            "clusterTime" : Timestamp(1535131703, 1),
            "signature" : {
                    "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                    "keyId" : NumberLong(0)
            }
    }
    }

因此,在我的Node.js应用程序上,我尝试通过以下方式连接到此副本集:

    const express = require('express');
    const { MongoClient } = require('mongodb');
    const debug = require('debug') 
    ('app:adminRoutes');
    const books = [{'a bunch of stuff'}]
    const adminRouter = express.Router();

    function router(nav) {
    adminRouter.route('/')
    .get((req, res) => {
    const url = 'mongodb://'
  + 'localhost:30001,'
  + 'localhost:30002,'
  + '/libraryApp?replicaSet=mongo-rs&readPreference=secondaryPreferred';
    const dbName = 'libraryApp';
    (async function mongo() {
    let client;
    try {
      client = await MongoClient.connect(url);
      debug('Connected to the server');
      const db = client.db(dbName);
      const response = await 
      db.collection('books').insertMany(books);
      res.json(response);
      debug(nav);
    } catch (err) {
      debug(err.stack);
    }
    client.close();
    }());
    });
   return adminRouter;
    }
   module.exports = router;

这终于是我遇到的问题。我不确定连接字符串是否错误或什么错误,因为整个Internet都以相同的方式进行操作。可能是异步函数这样做了吗?

这是输出:

    [nodemon] starting `node app.js`
    app listening on port 4000 +0ms
    app:bookRoutes Trying to connect to MongoDB using MongoClient. +0ms



    ../node_modules/mongodb/lib/topologies/replset.js:368
          throw err;
          ^

1 个答案:

答案 0 :(得分:0)

使用主机名代替0.0.0.0,不使用端口,即mongodb://mongodb-primary,mongodb-secondary/?replicaset=mongo-rsdocker-compose将完成所有联网。