Compass unable to connect to instance with replica set

I’m launching mono from a container with:

docker run --rm -it -e MONGO_INITDB_ROOT_USERNAME=mongo -e MONGO_INITDB_ROOT_PASSWORD=mongo -P -v $PWD/init-keyfile.sh:/docker-entrypoint-initdb.d/01-init-keyfile.sh mongo:latest --replSet rs0 --keyFile /tmp/mongodb-keyfile

After it’s running, I execute mongosh -u $MONGO_INITDB_ROOT_USERNAME -p $MONGO_INITDB_ROOT_PASSWORD --eval "try{rs.status().ok}catch(e){rs.initiate({\"_id\":\"rs0\",members:[{\"_id\":1,\"host\":\"127.0.0.1:27017\"}]}).ok}" --quiet

When I try to connect with Compass with the connection string mongodb://mongo:mongo@localhost:<ip> I always get this error:

connect ECONNREFUSED 127.0.0.1:27017

There was a problem connecting to mongodb:27017

But my application using the C# driver is able to connect.

What am I doing wrong?

Hi @Paulo_Morgado

The -P option to docker assigns a free port to bind on the docker host side. It would be more usual to see the form -p 27017:27017 used.

If using -P is desired use the docker ports command to discover what port was assigned.

10:49 $ docker run --rm -d -P --name post305877 mongo:8
949ab7847c3be53facdfe41aec5960a526db98691f02703fe9b960947dc9ad80

10:49 $ docker port post305877
27017/tcp -> 0.0.0.0:32770
27017/tcp -> [::]:32770

10:49 $ mongosh --port 32770 --eval 'db.adminCommand({listDatabases:1})'
{
  databases: [
    { name: 'admin', sizeOnDisk: Long('8192'), empty: false },
    { name: 'config', sizeOnDisk: Long('12288'), empty: false },
    { name: 'local', sizeOnDisk: Long('8192'), empty: false }
  ],
  totalSize: Long('28672'),
  totalSizeMb: Long('0'),
  ok: 1
}

Thank you for you help, but I know how to get the port dynamically exposed by docker.

I have more than one mongo container running at the same time and they can’t all be at port 27027.

So, how do I connect to those mongo databases using Compass?

Use the port that was dynamically assigned.

You haven’t tried it. Have you?

Yes, a great many times in fact.

The replica set member is defined on 127.0.0.1:27017 what is used in the connection string are seed hosts. The drivers connect to the seed host and retrieve the topology in this case `127.0.0.1:27017

As docker is actually bound to another port the connection will fail.

Add directConnection=true to the connection string. e.g. mongodb://localhost:32770/?directConnection=true

That’s it!

Why doesn’t the C# driver require it? Is it something other drivers need?

With a single host C# driver appears to connect in directConnection=true mode. If the connecion string / contains multiple hosts or the options replicaSet or directConnection=false then cluster discovery is in use.

ref:
https://www.mongodb.com/docs/drivers/csharp/current/fundamentals/connection/connect/#connect-to-a-replica-set

1 Like