Testcontainer cannot configure port binding
Asked Answered
A

3

14

I'm using testcontainer version 1.15.2. Tests are run in intellij on windows 10. I have a wiremock container. By default it listens on the port 8080. I would like to map this port to let's say 8081. So I do:

public WiremockContainer() {
    super("wiremock/wiremock:2.9.0-alpine");

    self()
            .waitingFor(Wait.forLogMessage(".*port:\\s*8080.*", 1)
                    .withStartupTimeout(Duration.ofSeconds(25L)))
            .withCreateContainerCmdModifier(cmd -> cmd.getHostConfig()
                    .withPortBindings(new PortBinding(Ports.Binding.bindPort(8081), new ExposedPort(8080)))
            )
            .withNetworkAliases("wiremock")
            .withExposedPorts(8081);
}

When the container is created it listens on the random port, not the 8081[1]. What am I doing wrong ? What should I do to make the container listen on 8081 instead of the random port ?

[1]

  1. I have another container that tries to connect on http://wiremock:8081 and keep getting Connection refused
  2. When I add: .waitingFor((...)forPort(8081)(...))); timeout occurs.
Alimony answered 23/11, 2021 at 17:48 Comment(0)
S
9

You cannot choose which actual port is used on the host machine. TestContainers chooses one automatically and makes it accessible through getMappedPort(containerPort) method on the container instance. You can also use getFirstMappedPort() if you only have one.

Integer hostPort = container.getMappedPort(8080);
Integer hostPort = container.getFirstMappedPort();

https://www.testcontainers.org/features/networking/

Shipmaster answered 24/11, 2021 at 10:58 Comment(0)
M
19

You can use set port bindings

List<String> portBindings = new ArrayList<>();
portBindings.add("5673:5672"); // hostPort:containerPort
portBindings.add("15673:15672"); // hostPort:containerPort
container.setPortBindings(portBindings);
Matchmaker answered 30/6, 2023 at 10:8 Comment(0)
S
9

You cannot choose which actual port is used on the host machine. TestContainers chooses one automatically and makes it accessible through getMappedPort(containerPort) method on the container instance. You can also use getFirstMappedPort() if you only have one.

Integer hostPort = container.getMappedPort(8080);
Integer hostPort = container.getFirstMappedPort();

https://www.testcontainers.org/features/networking/

Shipmaster answered 24/11, 2021 at 10:58 Comment(0)
H
0

Here is the alternative way to bind the port

container.withCreateContainerCmdModifier(cmd -> {
     cmd.getHostConfig().withPortBindings(
         new PortBinding(Ports.Binding.bindPort(5673),
         new ExposedPort(5672)));
});
Hydrocortisone answered 20/11, 2023 at 8:54 Comment(1)
Doesn't work. Container created without any bindingsKiddush

© 2022 - 2024 — McMap. All rights reserved.