Docker: Sharded mongodb in testcontainers

Hi everyone,

I’m currently integrating MongoDB with a Rust application and have written some integration tests using the testcontainers crate to initiate a MongoDB instance. My application utilizes change streams, necessitating the use of a sharded MongoDB setup.

I modified my testcontainer setup as follows to accommodate a sharded instance:

async fn start_mongodb() {
    let docker = Cli::default();
    let mongodb = docker.run(get_mongodb_image());
    let port = mongodb.get_host_port_ipv4(27017);
    println!("MongoDB started on port {}", port);

    let mut rx = MONGODB_IN.rx.lock().await;
    while let Some(command) = rx.recv().await {
        println!("Received container command: {:?}", command);
        match command {
            ContainerCommands::FetchConnectionString => 
                MONGODB_CONNECTION_STRING.tx.send(format!("mongodb://localhost:{}", port)).unwrap(),
            ContainerCommands::Stop => {
                mongodb.stop();
                rx.close();
            },
        }
    }
}

fn get_mongodb_image() -> RunnableImage<GenericImage> {
    let mongo_image = GenericImage::new("mongo", "7.0.7");
    let custom_args = vec![
        "mongod", "--replSet", "rs0", "--bind_ip", "0.0.0.0",
    ].into_iter().map(String::from).collect();

    RunnableImage::from((mongo_image, custom_args))
        .with_volume(("./tests/db-setup/mongo-init.js", "/docker-entrypoint-initdb.d/mongo-init.js"))
}

My mongo-init.js script initializes the replica set as follows:

rs.initiate({
  _id: "rs0",
  members: [{ _id: 0, host: "localhost:27017" }],
});

However, I encounter an issue due to the testcontainers setup using a random host system port (mapped to container port 27017), preventing connection failures when the port is already in use. When attempting to connect to the MongoDB server (either via Compass or my tests), the request is erroneously redirected to localhost:27017 (where no server instance exists), leading to connection failures. Strangely, using “Direct Connection” in Compass allows for a successful connection, indicating the server is running but the port redirection fails.

Is there a known solution to this problem, enabling MongoDB to run inside a Docker container without such port redirection issues?

Thank you for any insights or advice,
T