Convert Figma logo to code with AI

spotify logodocker-client

INACTIVE: A simple docker client for the JVM

1,432
549
1,432
66

Top Related Projects

Java Docker API Client

2,107

Docker container orchestration platform

Maven plugin for running and creating Docker images

Testcontainers is a Java library that supports JUnit tests, providing lightweight, throwaway instances of common databases, Selenium web browsers, or anything else that can run in a Docker container.

A Python library for the Docker Engine API

35,242

Define and run multi-container applications with Docker

Quick Overview

Spotify's docker-client is a Java library for interacting with Docker, providing a convenient way to manage Docker containers, images, and networks programmatically. It offers a high-level API that simplifies Docker operations and integrates well with Java applications.

Pros

  • Easy-to-use Java API for Docker operations
  • Supports a wide range of Docker features and commands
  • Well-maintained and actively developed by Spotify
  • Extensive documentation and examples available

Cons

  • May have a steeper learning curve for developers not familiar with Docker concepts
  • Dependency on Docker daemon, which needs to be running on the host system
  • Limited to Java applications, not suitable for other programming languages
  • May require additional configuration for certain Docker features or advanced use cases

Code Examples

  1. Creating and starting a container:
DockerClient docker = DefaultDockerClient.fromEnv().build();

ContainerConfig containerConfig = ContainerConfig.builder()
    .image("alpine:latest")
    .cmd("echo", "Hello, World!")
    .build();

ContainerCreation creation = docker.createContainer(containerConfig);
String id = creation.id();

docker.startContainer(id);
  1. Pulling an image:
DockerClient docker = DefaultDockerClient.fromEnv().build();

docker.pull("nginx:latest");
  1. Listing containers:
DockerClient docker = DefaultDockerClient.fromEnv().build();

List<Container> containers = docker.listContainers();
for (Container container : containers) {
    System.out.println(container.id() + " - " + container.image());
}

Getting Started

To use spotify/docker-client in your Java project, add the following dependency to your Maven pom.xml file:

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

For Gradle, add this to your build.gradle file:

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

Then, you can create a DockerClient instance and start using it in your code:

import com.spotify.docker.client.DefaultDockerClient;
import com.spotify.docker.client.DockerClient;

DockerClient docker = DefaultDockerClient.fromEnv().build();
// Use the docker client to interact with Docker

Make sure you have Docker installed and running on your system before using the library.

Competitor Comparisons

Java Docker API Client

Pros of docker-java

  • More actively maintained with frequent updates
  • Supports a wider range of Docker API features
  • Better documentation and examples

Cons of docker-java

  • Larger dependency footprint
  • Steeper learning curve for beginners
  • May have more complex setup for simple use cases

Code Comparison

docker-java:

DockerClient dockerClient = DockerClientBuilder.getInstance().build();
CreateContainerResponse container = dockerClient.createContainerCmd("nginx")
    .withName("my-nginx")
    .exec();
dockerClient.startContainerCmd(container.getId()).exec();

docker-client:

DockerClient docker = DefaultDockerClient.fromEnv().build();
ContainerConfig containerConfig = ContainerConfig.builder()
    .image("nginx")
    .build();
ContainerCreation creation = docker.createContainer(containerConfig);
docker.startContainer(creation.id());

Both libraries provide similar functionality for basic Docker operations. docker-java offers more granular control over container creation and management, while docker-client has a slightly more concise API for simple tasks.

docker-java is generally considered more feature-rich and up-to-date, making it suitable for complex Docker integrations. However, docker-client may be preferable for simpler use cases or projects that prioritize ease of use and minimal dependencies.

When choosing between the two, consider your project's specific requirements, the level of Docker API support needed, and the trade-offs between feature completeness and simplicity.

2,107

Docker container orchestration platform

Pros of Helios

  • Provides a complete container deployment and orchestration solution
  • Offers a user-friendly CLI and HTTP API for managing deployments
  • Supports advanced features like rolling updates and health checks

Cons of Helios

  • More complex setup and learning curve compared to docker-client
  • Limited to Helios-specific deployment workflows
  • Less flexibility for custom Docker operations

Code Comparison

Helios (Java):

HeliosClient client = HeliosClient.newBuilder()
    .setEndpoints("http://helios-master:5801")
    .build();
CreateJobResponse response = client.createJob(job).get();

docker-client (Java):

DockerClient docker = DefaultDockerClient.fromEnv().build();
ContainerCreation container = docker.createContainer(ContainerConfig.builder()
    .image("busybox").build());

Summary

Helios is a comprehensive container orchestration platform, while docker-client is a lightweight Java client for Docker API interactions. Helios offers more advanced deployment features but with increased complexity, whereas docker-client provides simpler, direct Docker operations with greater flexibility. The choice between them depends on specific project requirements and deployment strategies.

Maven plugin for running and creating Docker images

Pros of docker-maven-plugin

  • Tighter integration with Maven build lifecycle
  • Supports building and pushing Docker images directly from pom.xml
  • Provides extensive configuration options for Docker operations

Cons of docker-maven-plugin

  • Limited to Maven projects, not suitable for non-Maven Java applications
  • May have a steeper learning curve for developers unfamiliar with Maven plugins

Code Comparison

docker-maven-plugin configuration in pom.xml:

<plugin>
  <groupId>io.fabric8</groupId>
  <artifactId>docker-maven-plugin</artifactId>
  <configuration>
    <images>
      <image>
        <name>myapp:${project.version}</name>
        <build>
          <from>openjdk:11-jre</from>
          <assembly>
            <descriptorRef>artifact</descriptorRef>
          </assembly>
          <cmd>java -jar ${project.artifactId}-${project.version}.jar</cmd>
        </build>
      </image>
    </images>
  </configuration>
</plugin>

docker-client usage in Java:

DockerClient docker = DefaultDockerClient.fromEnv().build();
docker.pull("openjdk:11-jre");
ContainerConfig containerConfig = ContainerConfig.builder()
    .image("openjdk:11-jre")
    .cmd("java", "-jar", "myapp.jar")
    .build();
ContainerCreation creation = docker.createContainer(containerConfig);
docker.startContainer(creation.id());

Testcontainers is a Java library that supports JUnit tests, providing lightweight, throwaway instances of common databases, Selenium web browsers, or anything else that can run in a Docker container.

Pros of Testcontainers

  • Specifically designed for integration testing, providing a more focused and streamlined API for test environments
  • Offers a wide range of pre-configured containers for popular databases and services
  • Integrates well with popular testing frameworks like JUnit and TestNG

Cons of Testcontainers

  • Limited to Java ecosystem, while Docker Client supports multiple programming languages
  • Primarily focused on testing scenarios, may not be as flexible for general Docker management tasks
  • Steeper learning curve for developers not familiar with container-based testing

Code Comparison

Testcontainers:

@Container
PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:14");

@Test
void testWithPostgres() {
    // Use postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()
}

Docker Client:

DockerClient docker = DefaultDockerClient.fromEnv().build();
ContainerConfig config = ContainerConfig.builder()
    .image("postgres:14")
    .build();
ContainerCreation creation = docker.createContainer(config);
docker.startContainer(creation.id());

The Testcontainers example demonstrates its simplicity in setting up a test container, while the Docker Client code shows more low-level control over container creation and management.

A Python library for the Docker Engine API

Pros of docker-py

  • Official Docker SDK for Python, ensuring better compatibility and support
  • More comprehensive API coverage for Docker features
  • Actively maintained with frequent updates and bug fixes

Cons of docker-py

  • Steeper learning curve for beginners due to more complex API
  • Potentially slower performance for some operations compared to docker-client

Code Comparison

docker-py:

import docker

client = docker.from_env()
container = client.containers.run("ubuntu", "echo hello world", detach=True)
print(container.logs())

docker-client:

DockerClient docker = DefaultDockerClient.fromEnv().build();
ContainerCreation container = docker.createContainer(ContainerConfig.builder()
    .image("ubuntu").cmd("echo", "hello world").build());
docker.startContainer(container.id());

Additional Notes

Both libraries provide Docker API access for their respective languages. docker-py is more feature-complete and up-to-date, while docker-client offers a simpler API for basic operations. The choice between them depends on the specific project requirements, language preference, and desired level of Docker feature support.

35,242

Define and run multi-container applications with Docker

Pros of Compose

  • Official Docker tool for defining and running multi-container applications
  • Supports a wide range of Docker features and integrations
  • Active development with frequent updates and community support

Cons of Compose

  • Larger codebase and more complex than docker-client
  • Primarily focused on Docker Compose functionality, less flexible for custom Docker API interactions

Code Comparison

docker-client:

DockerClient docker = DefaultDockerClient.fromEnv().build();
ContainerConfig containerConfig = ContainerConfig.builder()
    .image("busybox").cmd("sh", "-c", "while :; do sleep 1; done")
    .build();
docker.createContainer(containerConfig);

Compose:

version: '3'
services:
  web:
    image: nginx:alpine
    ports:
      - "80:80"
  db:
    image: postgres:12

Summary

docker-client is a Java library for interacting with the Docker API, offering a more programmatic approach. Compose is a higher-level tool for defining and managing multi-container applications, using YAML files for configuration. While docker-client provides more flexibility for custom Docker interactions, Compose offers a more user-friendly approach for orchestrating complex container setups.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Docker Client

Build Status codecov Maven Central License

Status: mature

Spotify no longer uses recent versions of this project internally. The version of docker-client we're using is whatever helios has in its pom.xml. At this point, we're not developing or accepting new features or even fixing non-critical bugs. Feel free to fork this repo though.

This is a Docker client written in Java. It is used in many critical production systems at Spotify.

Version compatibility

docker-client is built and tested against the six most recent minor releases of Docker. Right now these are 17.03.1ce - 17.12.1ce (specifically the ones here). We upload the artifact tested on Docker 17.12.1~ce. See Docker docs on the mapping between Docker version and API version.

Download

Download the latest JAR or grab via Maven.

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

Usage Example

// Create a client based on DOCKER_HOST and DOCKER_CERT_PATH env vars
final DockerClient docker = DefaultDockerClient.fromEnv().build();

// Pull an image
docker.pull("busybox");

// Bind container ports to host ports
final String[] ports = {"80", "22"};
final Map<String, List<PortBinding>> portBindings = new HashMap<>();
for (String port : ports) {
    List<PortBinding> hostPorts = new ArrayList<>();
    hostPorts.add(PortBinding.of("0.0.0.0", port));
    portBindings.put(port, hostPorts);
}

// Bind container port 443 to an automatically allocated available host port.
List<PortBinding> randomPort = new ArrayList<>();
randomPort.add(PortBinding.randomPort("0.0.0.0"));
portBindings.put("443", randomPort);

final HostConfig hostConfig = HostConfig.builder().portBindings(portBindings).build();

// Create container with exposed ports
final ContainerConfig containerConfig = ContainerConfig.builder()
    .hostConfig(hostConfig)
    .image("busybox").exposedPorts(ports)
    .cmd("sh", "-c", "while :; do sleep 1; done")
    .build();

final ContainerCreation creation = docker.createContainer(containerConfig);
final String id = creation.id();

// Inspect container
final ContainerInfo info = docker.inspectContainer(id);

// Start container
docker.startContainer(id);

// Exec command inside running container with attached STDOUT and STDERR
final String[] command = {"sh", "-c", "ls"};
final ExecCreation execCreation = docker.execCreate(
    id, command, DockerClient.ExecCreateParam.attachStdout(),
    DockerClient.ExecCreateParam.attachStderr());
final LogStream output = docker.execStart(execCreation.id());
final String execOutput = output.readFully();

// Kill container
docker.killContainer(id);

// Remove container
docker.removeContainer(id);

// Close the docker client
docker.close();

Getting Started

If you're looking for how to use docker-client, see the User Manual. If you're looking for how to build and develop it, keep reading.

Prerequisites

docker-client should be buildable on any platform with Docker 1.6+, JDK8+, and a recent version of Maven 3.

A note on using Docker for Mac

If you are using Docker for Mac and DefaultDockerClient.fromEnv(), it might not be clear what value to use for the DOCKER_HOST environment variable. The value you should use is DOCKER_HOST=unix:///var/run/docker.sock, at least as of version 1.11.1-beta11.

As of version 4.0.8 of docker-client, DefaultDockerClient.fromEnv() uses unix:///var/run/docker.sock on OS X by default.

Testing

If you're running a recent version of docker (>= 1.12), which contains native swarm support, please ensure that you run docker swarm init to initialize the docker swarm.

Make sure Docker daemon is running and that you can do docker ps.

You can run tests on their own with mvn test. Note that the tests start and stop a large number of containers, so the list of containers you see with docker ps -a will start to get pretty long after many test runs. You may find it helpful to occasionally issue docker rm $(docker ps -aq).

Releasing

Commits to the master branch will trigger our continuous integration agent to build the jar and release by uploading to Sonatype. If you are a project maintainer with the necessary credentials, you can also build and release locally by running the below.

mvn clean [-DskipTests -Darguments=-DskipTests] -Dgpg.keyname=<key ID used for signing artifacts> release:prepare release:perform

A note on shading

Please note that in releases 2.7.6 and earlier, the default artifact was the shaded version. When upgrading to version 2.7.7, you will need to include the shaded classifier if you relied on the shaded dependencies in the docker-client jar.

Standard:

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

Shaded:

<dependency>
  <groupId>com.spotify</groupId>
  <artifactId>docker-client</artifactId>
  <classifier>shaded</classifier>
  <version>3.5.12</version>
</dependency>

This is particularly important if you use Jersey 1.x in your project. To avoid conflicts with docker-client and Jersey 2.x, you will need to explicitly specify the shaded version above.

Code of conduct

This project adheres to the Open Code of Conduct. By participating, you are expected to honor this code.