javadockerdocker-java

docker-java run container with -rm flag


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.


Solution

  • 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();