Communication between host and Container

In this post under TestContainer, I will show with example how to make the host communicate with the docker container.

Below is the complete code for your reference.

Main Class

1  package package3;
3  import org.testcontainers.containers.GenericContainer;
4  import org.testcontainers.utility.DockerImageName;
6  public class Example3 {
7      public static void main(String[] args) {
8          DockerImageName dockerImageName = DockerImageName.parse("testcontainers/helloworld:latest");
9          try (GenericContainer<?> container = new GenericContainer<>(dockerImageName).withExposedPorts(8081)) {
10             container.start();
11             System.out.println(container.getMappedPort(8081));
12             System.out.println("Done");
13         }
14     }
15 }

In the above code, at line 8, we created an instance of “DockerImageName” class using the “testcontainers/helloworld” image.

At line 9, we are creating a container using the image and also exposing the container’s port 8081 for communication by calling “withExposedPorts” method and passing 8081 as argument.

This doesn’t mean that the host can communicate with container at 8081 port.

TestContainer internally come up with a random port on host machine that is mapped to the container’s port 8081. Say for example 80851.

The host machine will then communicate with container using the randomly generated port.

In our example, the host machine will communicate with the container using 80851 port.

Any data sent to port 80851 on host machine is redirected to container’s port 8081.

To get the value of randomly assigned port we use the “getMappedPort” method on the “GenericContainer” instance passing the container port 8081 (for which we want randomly assigned host port). Refer to line 11.

Now open a browser and enter the url “http://localhost:80851&#8221; and press enter.

You will see “HelloWorld” page in the browser.

In this way host can communicate with docker containers.

Leave a Reply