Skip to content
Latchkey

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

Run this faster and cheaper on Latchkey managed runners. Start free →