3

In Java code I need to manage docker containers (restart, stop, start ...) using Docker-java library. https://github.com/docker-java/docker-java

In Docker-Java examples I found the way to create and get container: https://github.com/docker-java/docker-java/wiki

     DockerClient dockerClient = DockerClientBuilder.getInstance().build();
     CreateContainerResponse container = dockerClient.createContainerCmd("nginx")
            .exec();
     System.out.println(container.getId());
     dockerClient.restartContainerCmd(container.getId());

in command line we can use:

      docker container ls
      CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                NAMES
      4dd858fe9022        nginx               "nginx -g 'daemon of…"   42 hours ago        Up 42 hours         0.0.0.0:80->80/tcp   webserver

But I need to do it by JAVA code. I need to get the IDs for existing containers then get their Ip addresses and use restartContainerCmd method to restart it.

Hans Pour
  • 432
  • 6
  • 15
  • I think what you're looking for is this [interface](https://github.com/docker-java/docker-java/blob/master/src/main/java/com/github/dockerjava/api/command/ListContainersCmd.java#L14) , it has all of the methods you need to list containers. – Mousa Halaseh May 16 '19 at 22:11

2 Answers2

2

Found solution. Put it here in case if someone has same question:

Build a simple DockerClient then create ListContainersCmd object and use exec() method, then iterate through list of containers and find the container associates with IP and then get container Id; with Id we can restart container:

DockerClient dockerClient = DockerClientBuilder.getInstance().build();
ListContainersCmd listContainersCmd = dockerClient.listContainersCmd().withShowAll(true);
    for (Container container: listContainersCmd.exec()) {
        if (container.toString().contains("192.168.1.105")){
            dockerClient.restartContainerCmd(container.getId()).exec();
        }
    }
Hans Pour
  • 432
  • 6
  • 15
0

You may be looking for a utility method like this:

    void restartContainers(DockerClient dockerClient) {
        dockerClient.listContainersCmd().exec().stream()
            .map(Container::getId)
            .map(dockerClient::restartContainerCmd)
            .forEach(RestartContainerCmd::exec);
    }

Complete code on GitHub

Marco R.
  • 2,667
  • 15
  • 33