简体   繁体   中英

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM