Starting and Stopping Docker Containers

In this post under TestContainers, I will show with example how to start and stop a Docker container programmatically.

Below is the complete main class for your reference.

Main Class

1  package package1;
3  import org.testcontainers.containers.GenericContainer;
4  import org.testcontainers.utility.DockerImageName;
6  public class Example1 {
7      public static void main(String[] args) {
8          DockerImageName dockerImageName = DockerImageName.parse("hello-world:latest");
9          try (GenericContainer<?> container = new GenericContainer<>(dockerImageName)) {
10             container.start();
11         }
12     }
13 }

In the above code, at line 8, we create an instance of “DockerImageName” class by calling “parse” method and passing the image name as an argument.

In try with resource block, we are creating an instance of Docker Container using the class “GenericContainer” and passing the “DockerImageName” instance as an argument.

At line 10, we start the container by calling “start” method on docker container instance. This method will download the image if it is not already downloaded.

At the end of try with resource block, the container is automatically stopped as its class “GenericContainer” implements “AutoClosable” interface.

In this way we can start and stop a docker container programmatically.

Leave a Reply