How to Use GenericContainer for a Custom Image in Testcontainers
GenericContainer wraps any image, so when no dedicated module exists you configure ports, env, and wait strategy yourself.
Instantiate GenericContainer with an image, add .withExposedPorts(...), .withEnv(...), and a .waitingFor(...) strategy, then read getHost() and getMappedPort(...) to build the connection string.
Steps
- Create
new GenericContainer<>("image:tag"). - Add
.withExposedPorts(...)for each service port. - Add
.withEnv(...)for configuration. - Attach a wait strategy and read the mapped port after start.
Java example
CustomImageIT.java
GenericContainer<?> app = new GenericContainer<>("ghcr.io/acme/api:1.4.0")
.withExposedPorts(8080)
.withEnv("LOG_LEVEL", "debug")
.waitingFor(Wait.forHttp("/health").forStatusCode(200));
app.start();
String base = "http://" + app.getHost() + ":" + app.getMappedPort(8080);Gotchas
- Exposed ports are internal; the host-facing port is always the mapped one.
- Without a wait strategy the test may connect before the app is ready.
Related guides
How to Choose a Wait Strategy in Testcontainers for CIPick the right Testcontainers wait strategy (listening port, log message, or health check) so tests start onl…
How to Read Ephemeral Ports With getMappedPort in TestcontainersTestcontainers maps each exposed container port to a random free host port; read it with getMappedPort and ge…