mongodbdockerreplicasettestcontainersmongodb-replica-set

Docker Run MongoDB replica set.., how is it working?


So I'm creating some softwaare that makes heavy use of mongo transactions. So far, I've tried only with testcontainers mongo, and pure unit testing. Now I'm moving to test it manually and I get an error that says something like: Transaction numbers are only allowed on a replica set ..., yet that error doesn't happen during unit tests.

I read that this error happens because transactions are only possible on a replica set, but then, how is testcontainers working? I checked docker ps during running of tests and only one mongo docker container is up.

I checked the args passed by testcontainers, and it resulted they pass --replSet docker-rs. So I did, but then I get this error: NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.

I'm scratching my head bad, wondering how is testcontainers running a ONE mongo docker container that behaves like a replica set.


Solution

  • Assuming you're using Tescontainers MongoDB module, the missing part in your manual setup is most probably the mongo replica set initiation.

    This is mentioned in the testcontainers module docs as:

    Initialize a single replica set via executing a proper command

    Also feel free to take a look at the module sources itself to dig into implementation details. For example, initReplicaSet() part.