javatestcontainers

Configuring same network for multiple generic containers does not work


I am trying to create multiple containers using testcontainers lib which are sharing the same Network. What do I have right now is the following:

network = Network.newNetwork();

container1 = new GenericContainer<>().withNetwork(network)...
container2 = new GenericContainer<>().withNetwork(network)...

// variables' type and other builder details omitted for brevity

The container startup works fine, but when I do a docker inspect for each of these containers, I see that only container1 is assigned to the freshly created network. Any reason why this is happening?


Solution

  • It turns out that those "details omitted for brevity" did the difference. There was such a coincidence that the first container I tried to start had the following configuration:

    .withCreateContainerCmdModifier(cmd -> cmd.getHostConfig().withPortBindings(
            new PortBinding(Ports.Binding.bindPort(8443), new ExposedPort(8443)),
            new PortBinding(Ports.Binding.bindPort(8080), new ExposedPort(8080))))
     
    

    and the second container:

    .withCreateContainerCmdModifier(
            createContainerCmd -> createContainerCmd.withHostConfig(new HostConfig().withPortBindings(
                    new PortBinding(Ports.Binding.bindPort(9042), new ExposedPort(9042)),
                    new PortBinding(Ports.Binding.bindPort(9142), new ExposedPort(9142)))))
    

    Note the important difference between these two - getHostConfig() and withHostConfig(new HostConfig()). The second one, of course, overrides any network configuration set initially.

    Fixed by using getHostConfig() for both containers.