FabioCosta
FabioCosta

Reputation: 2749

How to use an existent network with testcontainers?

I have a test that will run with some controlled containers on an environment that already have an existent external docker network.

How can I make my test container connect to said network?

I tried the code bellow with no success:

        public  static final GenericContainer tcpController;
        static  {
            Network network = Network.builder().id("existent-external-network").build();
            tcpController = new GenericContainer("tcp_controller:0.0.1")
                    .withExposedPorts(3005)
                    .withEnv("TCP_PORT", "3005")
                    .withNetwork(network);

            tcpController.start();
        }

Essentially I want to do the equivalent of the following docker-compose

version: "3.4"
services:
  machine:
    image: tcp_controller:0.0.1
    environment:
      - TCP_PORT=3005
networks:
  default:
    external:
      name: existent-external-network

EDIT 1:

What Vitaly suggested worked.

Here is what I actually did using his suggestions and the docs

Consider TcpHandler just a class that needed the IP and port


    public static final DockerComposeContainer compose;

    static {
        compose = new DockerComposeContainer(
                new File("src/test/java/docker-compose.yml")
        )
                .withExposedService("machine", 3005)
                .withLocalCompose(true);
        compose.start();
    }

    @BeforeAll
    static void setup() throws IOException, TimeoutException {

        settings = Settings.getInstance();
        // We need to get the actual host and port using service name
        settings.tcpURL = compose.getServiceHost("machine", 3005);
        settings.tcpPort = compose.getServicePort("machine", 3005);
        tcp = new TCPHandler(settings.tcpURL, settings.tcpPort);
        tcp.start();

    }

Upvotes: 1

Views: 1699

Answers (1)

Vitaly Chura
Vitaly Chura

Reputation: 860

Fabio, not sure if you tried that - would using docker with local compose work for you? Like:

@Container
public static DockerComposeContainer docker = new DockerComposeContainer(
        new File("src/test/resources/compose-mysql-test.yml")
)
        .withLocalCompose(true);

Upvotes: 1

Related Questions