testcontainers/testcontainers-java · error · ReplicaSetInitializationException

An error occurred

Error message

An error occurred: %s

What it means

During replica set initialization, MongoDBContainer runs mongo CLI commands inside the container. checkMongoNodeExitCode inspects the ExecResult; a non-zero exit code means the mongo node command failed, so the stdout is formatted into this message and thrown as ReplicaSetInitializationException.

Solutions

  1. Check the stdout embedded in the message for the underlying mongo error
  2. Use an official, supported mongo image (DockerImageName.parse("mongo:x.y"))
  3. Ensure the image does not enable auth or conflicting replica settings at startup
  4. Increase logging (follow container output) to capture the failing command

Example fix

// before
MongoDBContainer mongo = new MongoDBContainer("mycompany/mongo-custom:latest"); // shell missing -> eval fails
// after
MongoDBContainer mongo = new MongoDBContainer(DockerImageName.parse("mongo:6.0"));
Defensive patterns

Strategy: try-catch

Try / catch

try {
    mongo.start();
} catch (ReplicaSetInitializationException e) {
    // stdout of the failed mongo command is embedded in the message
    throw new IllegalStateException("Replica set init command failed: " + e.getMessage(), e);
}

Prevention

When it happens

Trigger: initReplicaSet() executes an rs.initiate/eval command that exits non-zero (mongo binary missing in the image, authentication enabled on the image, unsupported image variant, corrupted container state).

Common situations: Using a custom or slim MongoDB image without the mongod/mongo shell; connecting to an image with auth pre-enabled; version mismatch where the eval command syntax is unsupported.

Understand the failure class

Background: Database query failed: Internal Server Error 500s wrapping SQL, Prisma, and connection failures — what to check first — this error's family across 16 libraries.

Related errors


AI-assisted analysis of testcontainers/testcontainers-java@8e549514e3 (2026-09-12). Data as JSON: /api/errors/b7b0d1393b2d448f. Report an issue: GitHub.

Appendix: source

Thrown at modules/mongodb/src/main/java/org/testcontainers/containers/MongoDBContainer.java:143

        if (!isRunning()) {
            throw new IllegalStateException("MongoDBContainer should be started first");
        }
        return getConnectionString() + "/" + databaseName;
    }

    private String[] buildMongoEvalCommand(final String command) {
        return new String[] {
            "sh",
            "-c",
            "mongosh mongo --eval \"" + command + "\"  || mongo --eval \"" + command + "\"",
        };
    }

    private void checkMongoNodeExitCode(final Container.ExecResult execResult) {
        if (execResult.getExitCode() != CONTAINER_EXIT_CODE_OK) {
            final String errorMessage = String.format("An error occurred: %s", execResult.getStdout());
            log.error(errorMessage);
            throw new ReplicaSetInitializationException(errorMessage);
        }
    }

    private String buildMongoWaitCommand() {
        return String.format(
            "var attempt = 0; " +
            "while" +
            "(%s) " +
            "{ " +
            "if (attempt > %d) {quit(1);} " +
            "print('%s ' + attempt); sleep(100);  attempt++; " +
            " }",
            "db.runCommand( { isMaster: 1 } ).ismaster==false",
            AWAIT_INIT_REPLICA_SET_ATTEMPTS,
            "An attempt to await for a single node replica set initialization:"
        );
    }

View on GitHub (pinned to 8e549514e3)