4

I am running a container with name tag which allows me to identify it.In docker-java,it requires container id for most of the operations and i do not know how to get that using docker-java.Can anyone help me how to get the container Id for the running container?

For example:

docker ps

    CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
8945dcd6195b        e7a064b1705a        "java '-Duser.time..."   4 days ago          Up 20 seconds                           runDataMock

I am looking for a way by which i could get the ContainerId using the ContainerNames.

NOTE: I am aware of the below method which creates a new container and picks the id. dockerClient.createContainerCmd(imageName).exec().getId()

Raj Asapu
  • 436
  • 5
  • 11

3 Answers3

1

You can filter the containers by status and by other properties using withXXX methods but there is not a WithNameFilter method in docker-java API. A workaround is to use a generic filter:

//get the docker client
DockerClient docker = DockerClientBuilder.getInstance(config).build();
//prepare command to retrieve the list of (running) containers 
ListContainersCmd listContainersCmd = client.listContainersCmd().withStatusFilter("running");
//and set the generic filter regarding name
listContainersCmd.getFilters().put("name", Arrays.asList("redis"));
//finally, run the command
List<Container> exec = listContainersCmd.exec();

and that's it!

Ricard Nàcher Roig
  • 1,271
  • 12
  • 14
0

If you are working with a local Docker Daemon, you could use https://www.github.com/amihaiemil/docker-java-api, version 0.0.1 has just been released.

To iterate over all the running containers, all you have to do is the following:

final Containers containers = new LocalDocker(
    new File("/var/run/docker.sock")
).containers();
for(final Container running : containers) {
    System.out.println(running.containerId());
}

Study the README of the project, the motivational blogpost and the wiki, they are quite short :)

amihaiemil
  • 623
  • 8
  • 19
0

Since this original posting date, the docker-java-api has gone through some updates. To update @amihaiemill's original answer to the updated api the code should be

final Docker docker = new UnixDocker( new File( "/var/run/docker.sock" ) );
final Containers containers = docker.containers();

for ( final Container running : containers ) {
    System.out.println( running.containerId() );
}

Thank you amihaiemil for your work on this project
Paul Stoner
  • 1,359
  • 21
  • 44