How to get list of existing containers ids by Docker-java

Hans Pour :

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 :

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();
        }
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=77266&siteId=1
Recommended