This user manual is made to correspond to Docker's API docs (e.g. API 1.18).
- Creating a DockerClient
- Containers
- List containers
- Create a container
- Inspect a container
- List processes running inside a container
- Get container logs
- Inspect changes on a container's filesystem
- Export a container
- Get container stats based on resource usage
- Resize a container TTY
- Start a container
- Stop a container
- Restart a container
- Kill a container
- Rename a container
- Pause a container
- Unpause a container
- Attach to a container
- Attach to a container (websocket)
- Wait a container
- Remove a container
- Copy files or folders from a container
- Images
- Miscellaneous
- Check auth configuration
- Display system-wide information
- Show the docker version information
- Ping the docker server
- Create a new image from a container’s changes
- Monitor Docker’s events
- Get a tarball containing all images in a repository
- Get a tarball containing all images.
- Load a tarball with a set of images and tags into docker
- Image tarball format
- Exec Create
- Exec Start
- Exec Resize
- Exec Inspect
- Mounting volumes in a container
// Create a client based on DOCKER_HOST and DOCKER_CERT_PATH env vars
final DockerClient docker = DefaultDockerClient.fromEnv().build();
// or use the builder
final DockerClient docker = DefaultDockerClient.builder()
// Set various options
.build();
Both DefaultDockerClient.builder()
and DefaultDockerClient.fromEnv()
return a
DefaultDockerClient.Builder
. The builder can be used to configure and build clients with custom
timeouts, connection pool sizes, and other parameters.
Unix socket support is available on Linux since v2.5.0:
final DockerClient docker = new DefaultDockerClient("unix:///var/run/docker.sock");
We can connect to HTTPS-secured Docker instances
with client-server authentication. The semantics are similar to using the DOCKER_CERT_PATH
environment variable:
final DockerClient docker = DefaultDockerClient.builder()
.uri(URI.create("https://boot2docker:2376"))
.dockerCertificates(new DockerCertificates(Paths.get("/Users/rohan/.docker/boot2docker-vm/")))
.build();
We use the Apache HTTP client under the covers, with a shared connection pool per instance of the Docker client. The default size of this pool is 100 connections, so each instance of the Docker client can only have 100 concurrent requests in flight.
If you plan on waiting on more than 100 containers at a time (DockerClient.waitContainer
), or
otherwise need a higher number of concurrent requests, you can modify the connection pool size:
final DockerClient docker = DefaultDockerClient.fromEnv()
.connectionPoolSize(SOME_LARGE_NUMBER)
.build()
Note that the connect timeout is also applied to acquiring a connection from the pool. If the pool
is exhausted and it takes too long to acquire a new connection for a request, we throw a
DockerTimeoutException
instead of just waiting forever on a connection becoming available.
final List<Container> containers = docker.listContainers();
// List all containers. Only running containers are shown by default.
final List<Container> containers = docker.listContainers(ListContainersParam.allContainers());
final ContainerCreation container = docker.createContainer(ContainerConfig.builder().build());
final ContainerInfo info = docker.inspectContainer("containerID");
Not implemented. PRs welcome.
final String logs;
try (LogStream stream = client.logs("containerID", LogsParam.stdout(), LogsParam.stderr())) {
logs = stream.readFully();
}
Not implemented. PRs welcome.
ImmutableSet.Builder<String> files = ImmutableSet.builder();
try (TarArchiveInputStream tarStream = new TarArchiveInputStream(docker.exportContainer(id))) {
TarArchiveEntry entry;
while ((entry = tarStream.getNextTarEntry()) != null) {
files.add(entry.getName());
}
}
final ContainerStats stats = docker.stats("containerID");
Not implemented. PRs welcome.
docker.startContainer("containerID");
docker.restartContainer("containerID");
// or with a seconds to wait before restarting parameter
docker.restartContainer("containerID", 10);
docker.killContainer("containerID");
docker.renameContainer("oldContainerID", "newContainerID");
docker.pauseContainer("containerID");
docker.unpauseContainer("containerID");
final String logs;
try (LogStream stream = docker.attachContainer(volumeContainer,
AttachParameter.LOGS, AttachParameter.STDOUT,
AttachParameter.STDERR, AttachParameter.STREAM)) {
logs = stream.readFully();
}
Not implemented. PRs welcome.
final ContainerExit exit = docker.waitContainer("containerID");
docker.removeContainer("containerID");
ImmutableSet.Builder<String> files = ImmutableSet.builder();
try (TarArchiveInputStream tarStream =
new TarArchiveInputStream(docker.copyContainer(id, "/bin"))) {
TarArchiveEntry entry;
while ((entry = tarStream.getNextTarEntry()) != null) {
files.add(entry.getName());
}
}
final List<Image> quxImages = docker.listImages(ListImagesParam.withLabel("foo", "qux"));
final AtomicReference<String> imageIdFromMessage = new AtomicReference<>();
final String returnedImageId = docker.build(
Paths.get(dockerDirectory), "test", new ProgressHandler() {
@Override
public void progress(ProgressMessage message) throws DockerException {
final String imageId = message.buildImageId();
if (imageId != null) {
imageIdFromMessage.set(imageId);
}
}
});
// By pulling
final AuthConfig authConfig = AuthConfig.builder().email(AUTH_EMAIL).username(AUTH_USERNAME)
.password(AUTH_PASSWORD).build();
docker.pull("dxia2/scratch-private:latest", authConfig);
// or by loading from a source
final File imageFile = new File("/path/to/image/file");
final String image = "busybox-test" + System.nanoTime();
try (InputStream imagePayload = new BufferedInputStream(new FileInputStream(imageFile))) {
docker.load(image, imagePayload);
}
final ImageInfo info = docker.inspectImage("imageID")
Not implemented yet. PRs welcome.
docker.push("imageID");
docker.pull("busybox:latest");
final String name = "testRepo/tagForce:sometag";
// Assign name to first image
docker.tag("busybox:latest", name);
// Force-re-assign tag to another image
docker.tag("busybox:buildroot-2014.02", name, true);
docker.removeImage("imageID");
final List<ImageSearchResult> searchResult = docker.searchImages("busybox");
final AuthConfig authConfig = AuthConfig.builder().email(AUTH_EMAIL).username(AUTH_USERNAME)
.password(AUTH_PASSWORD).build();
final int statusCode = docker.auth(authConfig);
assertThat(statusCode, equalTo(200));
final Info info = docker.info();
final Version version = docker.version();
final String pingResponse = docker.ping();
assertThat(pingResponse, equalTo("OK"));
// Pull image
docker.pull("busybox:latest");
// Create container
final ContainerConfig config = ContainerConfig.builder()
.image("busybox:latest")
.build();
final String name = randomName();
final ContainerCreation creation = docker.createContainer(config, name);
final String id = creation.id();
final String tag = "foobar";
final ContainerCreation newContainer = docker.commitContainer(
id, "mosheeshel/busybox", tag, config, "CommitedByTest-" + tag, "newContainer");
final ImageInfo imageInfo = docker.inspectImage(newContainer.id());
assertThat(imageInfo.author(), is("newContainer"));
assertThat(imageInfo.comment(), is("CommitedByTest-" + "foobar"));
docker.pull("busybox:latest");
final EventStream eventStream = docker.events();
final ContainerConfig config = ContainerConfig.builder()
.image("busybox:latest")
.build();
final ContainerCreation container = docker.createContainer(config, randomName());
docker.startContainer(container.id());
final Event createEvent = eventStream.next();
assertThat(createEvent.status(), equalTo("create"));
assertThat(createEvent.id(), equalTo(container.id()));
assertThat(createEvent.from(), startsWith("busybox:"));
assertThat(createEvent.time(), notNullValue());
final Event startEvent = eventStream.next();
assertThat(startEvent.status(), equalTo("start"));
assertThat(startEvent.id(), equalTo(container.id()));
assertThat(startEvent.from(), startsWith("busybox:"));
assertThat(startEvent.time(), notNullValue());
eventStream.close();
final File imageFile = save(BUSYBOX);
assertTrue(imageFile.length() > 0);
final File tmpDir = new File(System.getProperty("java.io.tmpdir"));
assertTrue("Temp directory " + tmpDir.getAbsolutePath() + " does not exist", tmpDir.exists());
final File imageFile = new File(tmpDir, "busybox-" + System.nanoTime() + ".tar");
imageFile.createNewFile();
imageFile.deleteOnExit();
final byte[] buffer = new byte[2048];
int read;
try (OutputStream imageOutput = new BufferedOutputStream(new FileOutputStream(imageFile))) {
try (InputStream imageInput = docker.save("busybox", authConfig)) {
while ((read = imageInput.read(buffer)) > -1) {
imageOutput.write(buffer, 0, read);
}
}
}
Not implemented yet. PRs welcome.
Not implemented yet. PRs welcome.
final String execId = docker.execCreate(containerId, new String[]{"sh", "-c", "exit 2"});
try (final LogStream stream = docker.execStart(execId)) {
stream.readFully();
}
final ExecState state = docker.execInspect(execId);
assertThat(state.id(), is(execId));
assertThat(state.running(), is(false));
assertThat(state.exitCode(), is(2));
assertThat(state.openStdin(), is(true));
assertThat(state.openStderr(), is(true));
assertThat(state.openStdout(), is(true));
}
See example above.
Not implemented yet. PRs welcome.
See example above.
To mount a host directory into a container, create the container with a HostConfig
.
You can set the local path and remote path in the binds()
method on the HostConfig.Builder
.
There are two ways to make a bind:
- Pass
binds()
a set of strings of the form"local_path:container_path"
. - Create a
Bind
object and pass it tobinds()
.
If you only need to create a volume in a container, and you don't need it to mount any
particular directory on the host, you can use the volumes()
method on the
ContainerConfig.Builder
.
final HostConfig hostConfig =
HostConfig.builder()
.appendBinds("/local/path:/remote/path")
.appendBinds(Bind.from("/another/local/path")
.to("/another/remote/path")
.readOnly(true)
.build())
.build();
final ContainerConfig volumeConfig =
ContainerConfig.builder()
.image("busybox:latest")
.volumes("/foo") // This volume will not mount any host directory
.hostConfig(hostConfig)
.build();
Be aware that, starting with API version 1.20 (docker version 1.8.x), information
about a container's volumes is returned with the key "Mounts"
, not "Volumes"
.
As such, the ContainerInfo.volumes()
method is deprecated. Instead, use
ContainerInfo.mounts()
.