Categories
Programming

Using docker-client in scala

Writing this post to give an overview of how to use the docker-client from Spotify in Scala.

First, get the latest stable docker-client dependency from maven for your project.

// https://mvnrepository.com/artifact/com.spotify/docker-client
libraryDependencies += "com.spotify" % "docker-client" % "8.16.0"

Creating the default client instance:

private val docker = DefaultDockerClient.fromEnv().build()

You can set the environment variable DOCKER_HOST according to the platform you are running it on.

Pulling an image:

val DOCKER_IMAGE = "ubuntu"
docker.pull(DOCKER_IMAGE)
Available docker images

Creating and starting a simple container:

  private val IMAGE_ID = "2ca708c1c9cc"
  private val hostConfig = HostConfig.builder().build()
  private val containerConfig = ContainerConfig.builder()
    .hostConfig(hostConfig)
    .image(IMAGE_ID)
    .cmd("sh", "-c", "while :; do sleep 1; done")
    .build()

  private val creation = docker.createContainer(containerConfig)

  private val id = creation.id()
  private val info = docker.inspectContainer(id)

  println(s"Starting container $id with $info")
  docker.startContainer(id)
You can see the container up and running with the docker stats command

Executing commands in the container and reading the output:

  def execWithOutput(command: Array[String]): String ={
    val execCreation = docker.execCreate(
      id, command, DockerClient.ExecCreateParam.attachStdout(),
      DockerClient.ExecCreateParam.attachStderr()
    )
    val output = docker.execStart(execCreation.id())
    output.readFully()
  }

  println(execWithOutput(Array("sh", "-c", "ls -lh")))
output from the command ls -lh

An example project is pushed to my github for further code exploration.

Leave a Reply

Your email address will not be published. Required fields are marked *