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()andgetMappedPort(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
getMappedPortbeforestart()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
How to Use GenericContainer for a Custom Image in TestcontainersRun any Docker image in tests with GenericContainer, setting exposed ports, env vars, and a wait strategy, th…
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 Network Containers Together in TestcontainersPut multiple Testcontainers on a shared Network and give them aliases so one container reaches another by nam…