javadockerspotify-docker-client

Spotify docker client not able to start container and execute command in one operation?


I have the following piece of code which enables me to start a Docker container and subsequently run a command with Stdout and Stderr attached. The issue here is that it starts the container, but of course exits the container before I'm able to exec a command inside the container. How can I start the container and exec a command inside the container(in this case ls) and keep stdout and stderr attached without getting the "cannot exec in a stopped state" error message?

final String IMAGE = "centos";

final DockerClient docker = new 
DefaultDockerClient("unix:///var/run/docker.sock");

docker.pull(IMAGE);

final ContainerConfig containerConfig = ContainerConfig.builder()
    .image(IMAGE)
    .build();


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

docker.startContainer(id);

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

Solution

  • You can start the container with an infinite sleep loop

    final ContainerConfig containerConfig = ContainerConfig.builder()
        .image(IMAGE)
        .cmd("sh", "-c", "while :; do sleep 1; done")
        .build();
    

    (This is the example from the Spotify documentation)