CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-com-spotify--docker-client

A comprehensive Docker client library for Java applications providing programmatic Docker API access with container lifecycle management, image operations, and Docker Swarm support.

Pending
Overview
Eval results
Files

index.mddocs/

Spotify Docker Client Java Library

The Spotify Docker Client is a comprehensive Java library that provides programmatic access to Docker Engine APIs. It offers complete container lifecycle management, image operations, network management, volume operations, and Docker Swarm support with type-safe parameter handling and immutable data classes.

Package Information

  • Package Name: docker-client
  • Package Type: maven
  • Language: Java
  • Installation: Maven dependency below

Core Imports

import com.spotify.docker.client.DockerClient;
import com.spotify.docker.client.DefaultDockerClient;
import com.spotify.docker.client.messages.*;
import com.spotify.docker.client.exceptions.DockerException;

Installation

Add the dependency to your Maven project:

<dependency>
    <groupId>com.spotify</groupId>
    <artifactId>docker-client</artifactId>
    <version>8.16.0</version>
</dependency>

For Gradle projects:

implementation 'com.spotify:docker-client:8.16.0'

Basic Usage

Creating a Docker Client

import com.spotify.docker.client.*;
import com.spotify.docker.client.messages.*;
import com.spotify.docker.client.exceptions.DockerException;

// Create client from environment variables (DOCKER_HOST, DOCKER_CERT_PATH)
DockerClient docker = DefaultDockerClient.fromEnv().build();

// Or configure manually
DockerClient docker = DefaultDockerClient.builder()
    .uri("unix:///var/run/docker.sock")
    .connectionPoolSize(100)
    .build();

Container Basics

// Create and run a container
ContainerConfig config = ContainerConfig.builder()
    .image("nginx:latest")
    .exposedPorts("80/tcp")
    .build();

ContainerCreation container = docker.createContainer(config);
docker.startContainer(container.id());

// List containers
List<Container> containers = docker.listContainers();

// Stop and remove
docker.stopContainer(container.id(), 10);
docker.removeContainer(container.id());

Image Operations

// Pull an image
docker.pull("ubuntu:20.04");

// Build from Dockerfile
String imageId = docker.build(
    Paths.get("/path/to/dockerfile/directory"),
    "my-image:latest"
);

// List images
List<Image> images = docker.listImages();

Core API Components

DockerClient Interface

The primary interface for all Docker operations:

public interface DockerClient extends Closeable {
    // System operations
    String ping() throws DockerException, InterruptedException;
    Version version() throws DockerException, InterruptedException;
    Info info() throws DockerException, InterruptedException;
    
    // Container management
    List<Container> listContainers(ListContainersParam... params) throws DockerException, InterruptedException;
    ContainerCreation createContainer(ContainerConfig config) throws DockerException, InterruptedException;
    void startContainer(String containerId) throws DockerException, InterruptedException;
    void stopContainer(String containerId, int secondsToWaitBeforeKilling) throws DockerException, InterruptedException;
    
    // Image management  
    List<Image> listImages(ListImagesParam... params) throws DockerException, InterruptedException;
    void pull(String image) throws DockerException, InterruptedException;
    String build(Path directory, String name, BuildParam... params) throws DockerException, InterruptedException;
    
    // And 100+ more methods...
}

Builder Pattern

Most configuration objects use Google's AutoValue builder pattern:

ContainerConfig config = ContainerConfig.builder()
    .image("nginx:latest")
    .hostname("web-server")
    .env("ENV_VAR=value")
    .exposedPorts("80/tcp", "443/tcp")
    .build();

HostConfig hostConfig = HostConfig.builder()
    .portBindings(Map.of("80/tcp", List.of(PortBinding.of("0.0.0.0", "8080"))))
    .memory(512L * 1024 * 1024) // 512MB
    .cpuShares(512)
    .build();

Parameter Classes

Type-safe parameter classes for filtering and options:

// Container listing parameters
List<Container> running = docker.listContainers(
    ListContainersParam.withStatusRunning()
);

List<Container> labeled = docker.listContainers(
    ListContainersParam.withLabel("env", "production")
);

// Image listing parameters  
List<Image> danglingImages = docker.listImages(
    ListImagesParam.danglingImages()
);

Exception Handling

The library provides comprehensive exception handling:

import com.spotify.docker.client.exceptions.ContainerNotFoundException;
import com.spotify.docker.client.exceptions.NotFoundException;

try {
    ContainerInfo info = docker.inspectContainer("nonexistent");
} catch (ContainerNotFoundException e) {
    // Handle missing container
} catch (NotFoundException e) {
    // Handle general not found
} catch (DockerException e) {
    // Handle Docker API errors
}

Resource Management

Always close resources properly:

// Auto-closeable client
try (DockerClient docker = DefaultDockerClient.fromEnv().build()) {
    // Docker operations
}

// Log streams
try (LogStream logs = docker.logs(containerId, LogsParam.stdout())) {
    String output = logs.readFully();
}

// Event streams
try (EventStream events = docker.events()) {
    while (events.hasNext()) {
        Event event = events.next();
        System.out.println("Event: " + event.status());
    }
}

Sub-Documentation

This library covers extensive Docker functionality organized into specialized areas:

  • Client Configuration - Client setup, authentication, SSL certificates, and connection management
  • Container Operations - Complete container lifecycle including create, start, stop, exec, logs, and file operations
  • Image Management - Building, pulling, pushing, tagging, and managing Docker images
  • Network Management - Creating and managing Docker networks and container connectivity
  • Volume Operations - Docker volume creation, inspection, and lifecycle management
  • Docker Swarm - Full swarm mode support including services, tasks, nodes, secrets, and configs

Key Features

  • Comprehensive API Coverage: 186+ Java classes covering all Docker Engine APIs
  • Type Safety: Immutable message classes and type-safe parameter handling
  • Authentication: Multiple authentication strategies for private registries
  • Connection Management: HTTP/HTTPS, Unix sockets, connection pooling
  • Progress Tracking: Real-time progress handlers for long-running operations
  • Exception Handling: Specific exception types for different error conditions
  • Resource Streams: Streaming APIs for logs, events, and file operations
  • Docker Swarm: Complete orchestration support for production deployments

Quick Examples

Health Check Container

// Create a simple health check container
ContainerConfig config = ContainerConfig.builder()
    .image("nginx:latest")
    .healthcheck(HealthConfig.builder()
        .test("CMD curl -f http://localhost/ || exit 1")
        .interval(Duration.ofSeconds(30))
        .timeout(Duration.ofSeconds(10))
        .retries(3)
        .build())
    .build();

ContainerCreation container = docker.createContainer(config);
docker.startContainer(container.id());

Monitor Events

// Monitor Docker events in real-time
try (EventStream eventStream = docker.events(
    EventsParam.since(System.currentTimeMillis() / 1000),
    EventsParam.type(Event.Type.CONTAINER)
)) {
    while (eventStream.hasNext()) {
        Event event = eventStream.next();
        System.out.printf("Container %s: %s%n", 
            event.id(), event.status());
    }
}

The Spotify Docker Client provides a robust, production-ready foundation for Java applications that need to integrate with Docker infrastructure.

Install with Tessl CLI

npx tessl i tessl/maven-com-spotify--docker-client

docs

client-configuration.md

containers.md

images.md

index.md

networks.md

swarm.md

volumes.md

tile.json