Search code examples
c#.netmongodbdockertestcontainers

Mongo as replica set in Testcontainers in .NET


I am trying to run Mongo in Docker by using Testcontainers in dotnet. I don't have any issue when I use following code:

        Container = new MongoDbBuilder()
            .WithPortBinding("27017")
            .Build();

But with this default MongoDbBuilder I can not run it as replica set. I found I have to run it as container builder with custom image:

        Container = new ContainerBuilder()
            .WithImage("mongo:6.0")
            .WithEntrypoint("mongod")
            .WithCommand("--replSet", "rs0")
            .WithPortBinding("27017")
            .Build();

Then I init replica set as:

    var result = Container.ExecAsync(new List<string>
    {
        "mongosh", "--eval", "rs.initiate()"
    }).GetAwaiter().GetResult();

When I try to do any operation with mongo in dotnet code, I get timeout error. When I run it in debug mode and try to connect to created docker by Mongo client (I use DataGrip), I get timeout error too. When I connect directly in docker container console by mongosh it works.

Docker running image:

enter image description here

Connection settings in Mongo client:

enter image description here

When I use MongoDbBuilder, as mentioned at the beginning, the Mongo client with connection string works.


Solution

  • Moving mongod to command worked for me:

    var container = new ContainerBuilder()
            .WithImage("mongo:6.0")
            .WithCommand("mongod", "--replSet", "rs0")
            .WithPortBinding("27017")
            .Build();
    

    Do not forget to switch to "No auth" since default docker image setup does not require auth (unlike the one created by MongoDbBuilder):

    By default Mongo's configuration requires no authentication for access, even for the administrative user.

    enter image description here

    enter image description here