Skip to content

Containers API

Mihai edited this page Apr 20, 2020 · 7 revisions

Containers API:

final Docker docker = ...;
final Containers containers = docker.containers();

Iterate Running Containers

You can iterate over all of the running containers like this:

for(final Container running : containers) {
//...
}

Iterate All Containers

You can iterate over all containers like this:

for(final Container running : containers.all()) {
//...
}

Multiple Create Methods

You can create a Container by giving it the image's String name or by giving it a whole JsonObject config object while specifying a name for it or not.

final Container c1 = containers.create("hello-world")
final Container c2 = containers.create("containerName", "hello-world")
final Container c3 = containers.create(JsonObject)
final Container c4 = containers.create("containerName", JsonObject)

Of course, if you need a running Container, a more elegant solution is to use the Images API to pull an Image and run the container from it:

final Image img = ...;
final Container container = img.run();

Work With A Container

A Container represents the Container JSON resource in Docker as well as the API endpoints performing on this resource. Container implements javax.json.JsonObject and holds the JSON representation accurate at the moment of its instantiation.

Once you have an Container, here's what you can do with it:

final Container container = ...;
final JsonObject inspection = container.inspect();
final Logs logs = container.logs();
container.start();
container.stop();                                   
container.kill();
container.restart();
container.rename("newName");
container.pause();
container.unpause();
container.waitOn("not-running"|"next-exit"|"removed");
container.remove();
...

Filter Containers

You can use the filter(Map) method to filter the Containers:

final Containers original = docker.containers;
final Containers filtered = original.filter(...);//multiple calls to filter will use all specified filters.
for(final Container ctn : filtered.all()) {
    //filtered containers here
}