I want to use the bitnami/mongodb
docker image to spin up a mongodb server for local development. I need to use a single node replica set as my project uses transactions. The image works fine when not configured as a replica set, but when it is Mongo Compass wont connect.
I'm using docker compose to start the container:
mongodb:
hostname: mongodb
image: bitnami/mongodb:latest
environment:
MONGODB_REPLICA_SET_MODE: primary
MONGODB_REPLICA_SET_NAME: rs0
MONGODB_REPLICA_SET_KEY: 12345
MONGODB_ROOT_PASSWORD: root
volumes:
- mongo-data:/data/db
restart: always
Trying to connect with the following URI comes back with a getaddrinfo ENOTFOUND mongodb
error:
mongodb://localhost:27017?replicaSet=rs0
Checking the container's output there doesnt seem to be much information other than it did receive the connection attempt then immediately ended.
2023-02-16 01:16:55 {"t":{"$date":"2023-02-16T09:16:55.854+00:00"},"s":"I", "c":"NETWORK", "id":22943, "ctx":"listener","msg":"Connection accepted","attr":{"remote":"127.0.0.1:54038","uuid":"87f2d8bc-d254-4824-b1f1-c27e0e9a4558","connectionId":12,"connectionCount":6}}
2023-02-16 01:16:55 {"t":{"$date":"2023-02-16T09:16:55.855+00:00"},"s":"I", "c":"NETWORK", "id":51800, "ctx":"conn12","msg":"client metadata","attr":{"remote":"127.0.0.1:54038","client":"conn12","doc":{"driver":{"name":"nodejs","version":"4.10.0"},"os":{"type":"Windows_NT","name":"win32","architecture":"x64","version":"10.0.22621"},"platform":"Node.js v16.5.0, LE (unified)|Node.js v16.5.0, LE (unified)","application":{"name":"MongoDB Compass Beta"}}}}
2023-02-16 01:16:55 {"t":{"$date":"2023-02-16T09:16:55.869+00:00"},"s":"I", "c":"NETWORK", "id":22944, "ctx":"conn12","msg":"Connection ended","attr":{"remote":"127.0.0.1:54038","uuid":"87f2d8bc-d254-4824-b1f1-c27e0e9a4558","connectionId":12,"connectionCount":5}}
If I disable the replica set I can connect just fine:
mongodb:
hostname: mongodb
image: bitnami/mongodb:latest
environment:
MONGODB_ROOT_PASSWORD: root
volumes:
- mongo-data:/data/db
restart: always
mongodb://root:root@localhost:27017
I found my answer through just playing around. What I believe is happening is the bitnami image is initalizing the replicaset with the nodes hostname mongodb
and in mongo. When connecting to a replicaset it then seems like its forwarded to try to connect to that hostname, which when running in a docker container often has its own network and is not available on your hosts network. Pinging mongodb
fails.
There's two possible solutions to this:
MONGODB_ADVERTISED_HOSTNAME: localhost
// C:\Windows\System32\drivers\etc\hosts
127.0.0.1 mongodb