Skip to content
Latchkey

How to Read Ephemeral Ports With getMappedPort in Testcontainers

Testcontainers binds each exposed port to a random free host port, so connect with getHost() and getMappedPort(), never the fixed internal number.

To avoid port collisions on shared CI runners, Testcontainers maps ports to ephemeral host ports. Always resolve the actual port with getMappedPort(internalPort) after the container starts.

Steps

  • Expose the internal port with withExposedPorts(...).
  • Start the container.
  • Read getHost() and getMappedPort(internalPort).
  • Build the connection string from those values.

Java example

MappedPortIT.java
GenericContainer<?> api = new GenericContainer<>("acme/api:1.0")
    .withExposedPorts(8080);
api.start();

String host = api.getHost();
int port = api.getMappedPort(8080);   // e.g. 49173
String base = "http://" + host + ":" + port;

Gotchas

  • Calling getMappedPort before start() throws "Mapped port can only be obtained after the container is started".
  • The mapped port changes every run, so never hardcode it in test config.

Related guides

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