In this post under TestContainers, I will show with example how to setup startup timeout.
Whenever we start a container whether through programmatically or through Docker Desktop or any other container management software, it takes time to start.
TestContainers to figure out whether a container has started or not, it waits for 60 sec so that the containers mapped port get ready to start listening.
If within 60 sec, the containers mapped port is not ready to listen for network request, TestContainers throws an exception and exits.
We can change this startup timeout to our need as shown in the main code using the method “withStartupTimeout”.
Main class
1 package package5;
2
3 import java.time.Duration;
4 import java.util.Scanner;
5
6 import org.testcontainers.containers.GenericContainer;
7 import org.testcontainers.utility.DockerImageName;
8
9 public class Example5 {
10 public static void main(String[] args) {
11 DockerImageName dockerImageName = DockerImageName.parse("tomcat:latest");
12 try (GenericContainer<?> container = new GenericContainer<>(dockerImageName).withExposedPorts(8080).withStartupTimeout(Duration.ofMinutes(1))) {
13 container.start();
14 System.out.println(container.getMappedPort(8080));
15 System.out.println("Type 'quit' to exit");
16 Scanner in = new Scanner(System.in);
17 String s = in.nextLine();
18 while(!"quit".equals(s)) {
19 s = in.nextLine();
20 }
21 }
22 }
23 }
In the above code, in try with resources block, I am creating an instance of “GenericContainer” class and then through method chaining performing the following actions
1) I am exposing the port 8080 on the container not the host machine by calling “withExposedPorts” method.
2) I am setting the startup timeout to 1 minute by calling “withStartupTimeout” method.
At line 13 we start the container.
From line 16 to 20 we wait for input from the user. If the user enters text “quit”, the program exists.
In this way I can configure the startup timeout.