While in a CI/CD environment for obvious reasons it is NOT recommended to fix a port binding for your containers, there might be instances (Kafka anyone?) where it might be preferable to grab a random port BEFORE the container is started AND force the binding to that port. This allows for easier configuration setup while your test suite boots up.
Once you have your random port, you need to configure your FixedHostPortGenericContainer to bind to it:
int port = findFreePort();
GenericContainer container = new FixedhostPortGenericContainer<>("IMAGE_NAME")
.withNetworkMode("host")
.withFixedExposedPort(port, port);
container.setPortBindings(Collections.singletonList(port + ":" + port));
which will configure the container to run in host network mode and will fix the host and container port to expose and bind to. In the Kafka example you could then set the KAFKA_ADVERTISED_LISTENERS environment variable directly in the container specification, since your port is now fixed.
No comments:
Post a Comment
With great power comes great responsibility