0

I am using docker-java to spawn new containers. I want to remove the containers after they are finished. Is there a way to achieve this with docker-java?

So I basically want something like

docker run --rm my-docker

with docker-java.

  • I am aware of the remove container function but I would prefer the to have this done automatically after the container stopped. – CoffeeKangaroo Jan 11 '20 at 10:50

1 Answers1

3

In the Docker HTTP API, the docker run --rm option translates to an AutoRemove option inside a HostConfig object. The Java API mirrors this object layout. The docker-java wiki doesn't have any good examples of using that object, but it's in the Java API too.

import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.model.HostConfig;

HostConfig hostConfig = HostConfig
  .newHostConfig()
  .withAutoRemove(true);             // Set the "remove" flag

CreateContainerResponse container = dockerClient
  .createContainerCommand("busybox")
  .withHostConfig(hostConfig)        // Add in the HostConfig object
  .exec();
David Maze
  • 130,717
  • 29
  • 175
  • 215