Skip to content
Advertisement

Run ES docker image with custom port using testcontainers

I want to run a container tests that running ES image via Docker. After some research I found https://www.testcontainers.org/ and they also have a built-it ES module.

Because my development environment using ES in ports 9200 and 9300 I prefer to use another ports for my tests, let’s say 1200 and 1300. Therefore, to run the docker image from CLI I use this command:

docker run -p 1200:9200 -p 1300:9300 -e "discovery.type=single-node" docker.elastic.co/elasticsearch/elasticsearch:7.6.2

I tried to do it with testcontainers, for example:

static ElasticsearchContainer esContainer =
        new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch:7.6.2")
                .withExposedPorts(1200, 9200)
                .withExposedPorts(1300, 9300)
                .withEnv("discovery.type", "single-node");
                // .waitingFor(Wait.forHttp("/")); // Wait until elastic start – cause an error

@BeforeClass
public static void initEsDockerImage() {
    esContainer.start();
    esContainer.isRunning();
}

breakpoint in esContainer.isRunning():

port is 32384, run esContainer.getHttpHostAddress() return localhost/127.0.0.1:32847 and also from docker dashboard: Anyway, failed to make ES connection with both (1200 and 32384).

run the start() line with the **waitingFor** command throws Container startup failed error

Another question, how can I know the schema (http or https) in testcontainers?

Advertisement

Answer

If you want to specify a port instead of using a random one, you can do it with this:

static final MySQLContainer<?> mysql =
    new MySQLContainer<>("mysql:5.6")
        .withExposedPorts(34343)
        .withCreateContainerCmdModifier(cmd -> cmd.withHostConfig(
            new HostConfig().withPortBindings(new PortBinding(Ports.Binding.bindPort(34343), new ExposedPort(3306)))
        ));
Advertisement