我有以下一段代码,它使我能够启动 Docker 容器并随后运行附加了 Stdout 和 Stderr 的命令。这里的问题是它启动了容器,但当然在我能够在容器内执行命令之前退出容器。如何启动容器并在容器内执行命令(在这种情况下ls
)并保持 stdout 和 stderr 连接而不会收到“无法在停止状态下执行”错误消息?
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();