如何在docker-php api中的docker execstart中进行stdin

问题描述 投票:0回答:2

我想与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();

提前致谢。

docker containers tty
2个回答
0
投票

有谁不帮我?这个问题非常重要


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'));
© www.soinside.com 2019 - 2024. All rights reserved.