The KafkaContainer in TestContainers hangs till timeout with "Timed out waiting for container port to open"

1.9k Views Asked by At

I am trying to start a kafka container in TestContainers. My code is looking like this:

import java.io.File;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.DockerComposeContainer;
import org.testcontainers.containers.KafkaContainer;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.containers.wait.strategy.Wait;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

@Testcontainers
public class FirstTest {

  @Container
  public static DockerComposeContainer environment =
      new DockerComposeContainer(new File("src/test/resources/compose-test.yml"))
          .withExposedService(
              "redis_1", 6379, Wait.forListeningPort().withStartupTimeout(Duration.ofSeconds(60)));

  @Container
  public static KafkaContainer kafka =
      new KafkaContainer()
          .waitingFor(Wait.forListeningPort().withStartupTimeout(Duration.ofSeconds(360)));

  @Container public PostgreSQLContainer postgresContainer = new PostgreSQLContainer();

  @Test
  void integrationTest() {

    String redisUrl =
        environment.getServiceHost("redis_1", 6379)
            + ":"
            + environment.getServicePort("redis_1", 6379);

    String jdbcUrl = postgresContainer.getJdbcUrl();
    String username = postgresContainer.getUsername();
    String password = postgresContainer.getPassword();

    String url = kafka.getBootstrapServers();
  }
}

When I run this code the thread hangs in running state until I receive a timeout exception:

Caused by: org.testcontainers.containers.ContainerLaunchException: Timed out waiting for container port to open (localhost ports: [32937, 32939] should be listening)

I want to mention that without the kafkaContainer everything works as expected. I am able to start the redis and postgres containers succesfully.

This is the kafkaContainer version which I use:

<dependency>
      <groupId>org.testcontainers</groupId>
      <artifactId>kafka</artifactId>
      <version>1.14.3</version>
      <scope>test</scope>
 </dependency>

1

There are 1 best solutions below

0
On

From what I see in the source code waitingFor(Wait.forListeningPort()) will only work if you previously exposed some ports. (I'm not 100% sure though.)

What if you just create a Kafka container without waitingFor() call?