如何在docker-php api中的docker execstart中进行标准输入

时间:2018-12-05 10:12:05

标签: docker containers tty

我想和bash互动。我从容器获得输出,但无法将任何内容发送到容器。
我想我应该和Tty做些什么。

$remoteSocket ='192.168.85.34:2375';
$ssl = false;
// Connect to Docker
$client = DockerClientFactory::create([
    'remote_socket' => $remoteSocket,
    'ssl' => $ssl
]);
$docker = Docker::create($client);
$config = new ContainersCreatePostBody();
$config->setTty(true);
$config->setOpenStdin(true);
$config->setAttachStderr(false);
$config->setAttachStdout(false);
$config->setAttachStdin(false);
$config->setStdinOnce(false);
$config->setImage("test:2");

$creation = $docker->containerCreate($config);
$docker->containerStart($creation->getId());
$execConfig = new ContainersIdExecPostBody();
$execConfig->setTty(true);
$execConfig->setAttachStdout(true);
$execConfig->setAttachStderr(true);
$execConfig->setAttachStdin(true);
$execConfig->setCmd(['/bin/bash']);

$execid = $docker->containerExec($creation->getId(),$execConfig)->getId();
$execStartConfig = new ExecIdStartPostBody();
$execStartConfig->setDetach(false);

// Execute the command
$stream = $docker->execStart($execid,$execStartConfig);
//var_dump($stream);die();
// To see the output stream of the 'exec' command
$stdoutText = "";
$stderrText = "";
$stream->onStdout(function ($stdout) use (&$stdoutText) {
    echo $stdout;
});
$stream->onStderr(function ($stderr) use (&$stderrText) {
    print_r("err: ".$stderr."\n");
});
$stream->wait();

谢谢。

2 个答案:

答案 0 :(得分:0)

有人没有帮助我吗? 这个问题非常重要

答案 1 :(得分:0)

我设法使它正常工作!

这是我的代码。将$command设置为要在正在运行的容器上执行的命令。

use Docker\API\Model\ContainersCreatePostBody;
use Docker\API\Model\ContainersIdExecPostBody;
use Docker\API\Model\ExecIdStartPostBody;
use Docker\Docker;
use Log;

$docker = Docker::create();

$containerConfig = new ContainersCreatePostBody();
$containerConfig->setImage('ubuntu:latest');
$containerConfig->setCmd(['bash']);
$containerConfig->setTty(true);

$containerCreateResult = $docker->containerCreate($containerConfig);
$containerId = $containerCreateResult->getId();

$docker->containerStart($containerId);

$execConfig = new ContainersIdExecPostBody();
$execConfig->setAttachStderr(true);
$execConfig->setAttachStdout(true);
$execConfig->setCmd($command);

$execId = $docker->containerExec($containerId, $execConfig)->getId();

$execStartConfig = new ExecIdStartPostBody();
$execStartConfig->setDetach(false);

$stream = $docker->execStart($execId, $execStartConfig);

$stream->onStdout(
    function ($buffer) use (&$output) {
        Log::debug('Stdout', compact('buffer'));
        $output .= $buffer;
    }
);

$stream->onStderr(
    function ($buffer) use (&$output) {
        Log::debug('Stderr', compact('buffer'));
        $output .= $buffer;

        $build->status = 'fail';
    }
);

$stream->wait();

$docker->containerStop($containerId);

Log::debug('Combined', compact('output'));