How do I fix ReplicaSetNoPrimary MongooseServerSelectionError when connecting to a local Mongo ReplicaSet from inside a Docker container?

Viewed 640

I am developing a Node.js app that I want to connect to a Mongo Replica Set and I run the MongoDB replica set locally using the run-rs npm module by executing run-rs --dbpath ./data --keep. When I run my application as a Node application, I successfully connect to the replica set with the following code

const db = mongoose.connect(config.db.url, config.db.options)
    .catch((error) => {
      logger.error('Error connecting to the database', error);
    });

Where the url and options are

debug: Mongoose connecting to mongodb://localhost:27017,localhost:27018,localhost:27019/my-app-dev?replicaSet=rs with options  {"service":"my-app","useNewUrlParser":true,"useUnifiedTopology":true,"useFindAndModify":false}
info: Mongoose successfully connected to mongodb://localhost:27017,localhost:27018,localhost:27019/my-app-dev?replicaSet=rs

When I run the application inside of my Docker container, I get the following

info: Mongoose disconnected from mongodb://host.docker.internal:27017,host.docker.internal:27018,host.docker.internal:27019/my-app-dev?replicaSet=rs {"service":"my-app"}
error: Error connecting to the database connect ECONNREFUSED 127.0.0.1:27017 {"service":"my-app","reason":{"type":"ReplicaSetNoPrimary","setName":"rs","maxSetVersion":1,"maxElectionId":"7fffffff0000000000000079","servers":{},"stale":false,"compatible":true,"compatibilityError":null,"logicalSessionTimeoutMinutes":null,"heartbeatFrequencyMS":10000,"localThresholdMS":15,"commonWireVersion":7},"stack":"MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017\n at NativeConnection.Connection.openUri (/src/node_modules/mongoose/lib/connection.js:800:32)\n at /src/node_modules/mongoose/lib/index.js:341:10\n at /src/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:5\n at new Promise ()\n at promiseOrCallback (/src/node_modules/mongoose/lib/helpers/promiseOrCallback.js:30:10)\n at Mongoose.connect (/src/node_modules/mongoose/lib/index.js:340:10)\n at Object. (/src/index.js:46:21)\n at Module._compile (internal/modules/cjs/loader.js:1138:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)\n at Module.load (internal/modules/cjs/loader.js:986:32)\n at Function.Module._load (internal/modules/cjs/loader.js:879:14)\n at Module.require (internal/modules/cjs/loader.js:1026:19)\n at require (internal/modules/cjs/helpers.js:72:18)\n at Object. (/src/server.js:3:13)\n at Module._compile (internal/modules/cjs/loader.js:1138:30)\n at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)"}

To connect to the replicaset from inside the container, I am using the following URI mongodb://host.docker.internal:27017,host.docker.internal:27018,host.docker.internal:27019/my-app-dev?replicaSet=rs

0 Answers
Related