Able to connect to containerized DB, but only without replica set

I use two docker containers: one for mongo and one for node.js. I was able to connect them both on the same docker network, but if I set replicaSet on a connection, I can’t connect, it fails. I’ve checked the mongo status and can confirm it’s set to replica, and I think I’ve tried everything - nothing helps.

I’m aware of that I’m trying to set replica on a single instance.

I’ve spend two days on this already…

  • update:
    I’ve tried to post all the relevant logs, but it says the following on submit: “is limited to 32000 characters; you entered 77453.”

Here’s what I get when I init my mongo container:
-deleted-

You can see below that replica is indeed set:

sudo docker exec mongo bash -c 'mongo --eval "rs.status();"'
MongoDB shell version v4.4.1
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("057d296e-b1da-4983-ada0-7b7407860fb2") }
MongoDB server version: 4.4.1
{
        "set" : "rs0",
        "date" : ISODate("2020-10-06T13:52:59.964Z"),
        "myState" : 1,
        "term" : NumberLong(2),
        "syncSourceHost" : "",
        "syncSourceId" : -1,
        "heartbeatIntervalMillis" : NumberLong(2000),
        "majorityVoteCount" : 1,
        "writeMajorityCount" : 1,
        "votingMembersCount" : 1,
        "writableVotingMembersCount" : 1,
        "optimes" : {
                "lastCommittedOpTime" : {
                        "ts" : Timestamp(1601992370, 1),
                        "t" : NumberLong(2)
                },
                "lastCommittedWallTime" : ISODate("2020-10-06T13:52:50.061Z"),
                "readConcernMajorityOpTime" : {
                        "ts" : Timestamp(1601992370, 1),
                        "t" : NumberLong(2)
                },
                "readConcernMajorityWallTime" : ISODate("2020-10-06T13:52:50.061Z"),
                "appliedOpTime" : {
                        "ts" : Timestamp(1601992370, 1),
                        "t" : NumberLong(2)
                },
                "durableOpTime" : {
                        "ts" : Timestamp(1601992370, 1),
                        "t" : NumberLong(2)
                },
                "lastAppliedWallTime" : ISODate("2020-10-06T13:52:50.061Z"),
                "lastDurableWallTime" : ISODate("2020-10-06T13:52:50.061Z")
        },
        "lastStableRecoveryTimestamp" : Timestamp(1601992350, 1),
        "electionCandidateMetrics" : {
                "lastElectionReason" : "electionTimeout",
                "lastElectionDate" : ISODate("2020-10-06T13:48:40.043Z"),
                "electionTerm" : NumberLong(2),
                "lastCommittedOpTimeAtElection" : {
                        "ts" : Timestamp(0, 0),
                        "t" : NumberLong(-1)
                },
                "lastSeenOpTimeAtElection" : {
                        "ts" : Timestamp(1601992117, 1),
                        "t" : NumberLong(1)
                },
                "numVotesNeeded" : 1,
                "priorityAtElection" : 1,
                "electionTimeoutMillis" : NumberLong(10000),
                "newTermStartDate" : ISODate("2020-10-06T13:48:40.050Z"),
                "wMajorityWriteAvailabilityDate" : ISODate("2020-10-06T13:48:40.105Z")
        },
        "members" : [
                {
                        "_id" : 0,
                        "name" : "127.0.0.1:27017",
                        "health" : 1,
                        "state" : 1,
                        "stateStr" : "PRIMARY",
                        "uptime" : 261,
                        "optime" : {
                                "ts" : Timestamp(1601992370, 1),
                                "t" : NumberLong(2)
                        },
                        "optimeDate" : ISODate("2020-10-06T13:52:50Z"),
                        "syncSourceHost" : "",
                        "syncSourceId" : -1,
                        "infoMessage" : "",
                        "electionTime" : Timestamp(1601992120, 1),
                        "electionDate" : ISODate("2020-10-06T13:48:40Z"),
                        "configVersion" : 1,
                        "configTerm" : 2,
                        "self" : true,
                        "lastHeartbeatMessage" : ""
                }
        ],
        "ok" : 1,
        "$clusterTime" : {
                "clusterTime" : Timestamp(1601992370, 1),
                "signature" : {
                        "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                        "keyId" : NumberLong(0)
                }
        },
        "operationTime" : Timestamp(1601992370, 1)
}

Here I’m establishing connection without replica(succesfuly):

sudo docker-compose up --build
Building app
Step 1/7 : FROM node:12
 ---> 28faf336034d
Step 2/7 : WORKDIR /usr/src/app
 ---> Using cache
 ---> 528954c980ed
Step 3/7 : COPY package*.json ./
 ---> Using cache
 ---> ac7231ed1e31
Step 4/7 : RUN npm install
 ---> Using cache
 ---> 599bd8e45d0e
Step 5/7 : COPY . .
 ---> Using cache
 ---> 7bef22e63d74
Step 6/7 : EXPOSE 5000
 ---> Using cache
 ---> 419cba388cef
Step 7/7 : CMD ["node", "index.js"]
 ---> Using cache
 ---> f45bf6120b98

Successfully built f45bf6120b98
Successfully tagged app_app:latest
Creating app ... done
Attaching to app
app    | Node app is running on port... 5000!
app    | Connected to  MongoDB...

And here I’m actually trying to set the replica set and it fails:

sudo docker-compose up --build
Building app
Step 1/7 : FROM node:12
 ---> 28faf336034d
Step 2/7 : WORKDIR /usr/src/app
 ---> Using cache
 ---> 528954c980ed
Step 3/7 : COPY package*.json ./
 ---> Using cache
 ---> ac7231ed1e31
Step 4/7 : RUN npm install
 ---> Using cache
 ---> 599bd8e45d0e
Step 5/7 : COPY . .
 ---> a7073f6db1f1
Step 6/7 : EXPOSE 5000
 ---> Running in 301b943c791a
Removing intermediate container 301b943c791a
 ---> 98c67ab84a1b
Step 7/7 : CMD ["node", "index.js"]
 ---> Running in 726ad8399f03
Removing intermediate container 726ad8399f03
 ---> 9e59e6e37f0e

Successfully built 9e59e6e37f0e
Successfully tagged app_app:latest
Creating app ... done
Attaching to app
app    | Node app is running on port... 5000!
app    | db error on connection MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
app    |     at NativeConnection.Connection.openUri (/usr/src/app/node_modules/mongoose/lib/connection.js:800:32)
app    |     at /usr/src/app/node_modules/mongoose/lib/index.js:341:10
app    |     at /usr/src/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:5
app    |     at new Promise (<anonymous>)
app    |     at promiseOrCallback (/usr/src/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:30:10)
app    |     at Mongoose.connect (/usr/src/app/node_modules/mongoose/lib/index.js:340:10)
app    |     at Object.<anonymous> (/usr/src/app/index.js:6:4)
app    |     at Module._compile (internal/modules/cjs/loader.js:1137:30)
app    |     at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
app    |     at Module.load (internal/modules/cjs/loader.js:985:32)
app    |     at Function.Module._load (internal/modules/cjs/loader.js:878:14)
app    |     at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
app    |     at internal/main/run_main_module.js:17:47 {
app    |   reason: TopologyDescription {
app    |     type: 'ReplicaSetNoPrimary',
app    |     setName: 'rs0',
app    |     maxSetVersion: 1,
app    |     maxElectionId: 7fffffff0000000000000002,
app    |     servers: Map { '127.0.0.1:27017' => [ServerDescription] },
app    |     stale: false,
app    |     compatible: true,
app    |     compatibilityError: null,
app    |     logicalSessionTimeoutMinutes: null,
app    |     heartbeatFrequencyMS: 10000,
app    |     localThresholdMS: 15,
app    |     commonWireVersion: 9
app    |   }
app    | }

My connection string when connecting with replica set:
mongoose
.connect(“mongodb://mongo:27017/?replicaSet=rs0”, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
})
.then(() => console.log(“Connected to MongoDB…”))
.catch((err) => console.log(“db error on connection”, err));

Hi @letoke8464_leto and welcome in the MongoDB Community :muscle: !

There is nothing to really work with here to help you debug this. Would it be possible for you to share all that code in a public Github maybe? Especially all the docker & docker-compose files you are using?

It’s possible that the MongoDB single node RS isn’t completely set up & ready yet when the NodeJS application is trying to connect to it.

Cheers,
Maxime.

Indeed, I probably not setting it right(despite it connects without replica set successfully). Hopefully we could resolve this together with your help.

Regards the possibility that MongoDB isn’t completely ready at the moment NodeJS is trying to connect:
I connect them manually, first the MongoDB container and only then NodeJS. Also, before I start NodeJS, I check if replica is indeed set on the mongo, I’ve posted log in my first message.

I will post my code here, if you do need some more info, please tell me.

Mongo Container (docker-compose):

version: "3.7"
services:
  mongo:
    container_name: mongo
    hostname: mongo
    build: .
    expose:
      - "27017"
    ports:
      - "27017:27017"
    networks:
      - resolute

networks:
  resolute:
      name: resolute

Mongo Container (Dockerfile):

  • I’ve tried to connect to host mongo:27017 instead of 127.0.0.1, but then I can’t get replica set when I check it via terminal.

    FROM mongo
    RUN echo “rs.initiate({’_id’:‘rs0’, ‘members’:[{’_id’:0,‘host’:‘127.0.0.1:27017’}]});” > /docker-entrypoint-initdb.d/replica-init.js
    RUN cat /docker-entrypoint-initdb.d/replica-init.js
    CMD [ “–bind_ip_all”, “–replSet”, “rs0” ]

NodeJS Container(docker-compose):

version: "3.7"
services:
  app:
    container_name: app
    hostname: app
    build: .
    expose:
      - "5000"
    ports:
      - "5000:5000"
    networks:
      - innerResolute

networks:
  innerResolute:
    external:
      name: resolute

NodeJS Container (Dockerfile):

FROM node:12

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 5000

CMD ["node", "index.js"]

NodeJS Container (index.js ):

const express = require("express");
const mongoose = require("mongoose");
const app = express();

mongoose
  .connect("mongodb://mongo:27017/?replicaSet=rs0", {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
    useFindAndModify: false
  })
  .then(() => console.log("Connected to MongoDB..."))
  .catch((err) => console.log("db error on connection", err));

app.get("/", (req, res) => {
  res.send("Node app is up and running...");
});

app.listen(5000, () => {
  console.log("Node app is running on port... 5000!");
});

Let me know if you need extra info on anything.

Don’t use 127.0.0.1 for the replica name in the rs.init().

It needs to be addressable. Make it mongo1 say, make sure the container name matches so other containers can resolve it.

2 Likes

Thanks to both of you I was able to resolve this. Thanks a lot!

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.