【问题标题】:Accessing the output of a command running in a docker container访问在 docker 容器中运行的命令的输出
【发布时间】:2022-07-22 14:17:08
【问题描述】:

我正在尝试从 docker-java 0.10.3 升级到 3.2.7。这条线让我完全被难住了:

InputStream response = 
  dockerClient.attachContainerCmd(container.getId())
    .withLogs(true)
    .withStdErr(true)
    .withStdOut(true)
    .withFollowStream(true)
    .exec();

我已经设法通过将其更改为来解决第一个错误

InputStream response = 
  dockerClient.attachContainerCmd(container.getId())
    .withLogs(true)
    .withStdErr(true)
    .withStdOut(true)
    .withFollowStream(true)
    .exec(new AttachContainerResultCallback());

(但我的 IDE 说 AttachContainerResultCallback 已弃用。)问题是 .exec() 曾经返回 InputStream。现在它返回一个void。我需要InputStream,因为在容器中运行的命令的输出需要找到它到屏幕的方式。这需要是实时的,因为用户需要在命令运行时看到它们的输出;我不能只在最后复制一个文件。

我怎样才能得到这个InputStream


错误是:

java: incompatible types: inference variable T has incompatible bounds
    lower bounds: java.io.InputStream,com.github.dockerjava.api.async.ResultCallback<com.github.dockerjava.api.model.Frame>
    lower bounds: com.github.dockerjava.core.command.AttachContainerResultCallback

【问题讨论】:

  • 为什么不是 3.2.12?因为我刚开始的时候3.2.7是最新的。我不是程序员(我是硬件工程师),所以进展缓慢。我已经设法进行了一些更改(它们可以编译,但我不知道它们是否有效。)但是我现在一直在寻找几天(打开和关闭),以找到一些返回 InputStream 的方法。但是好像一个也没有。似乎也很少有文档。即使我是程序员,我也不明白我怎么能解决这个问题。

标签: java docker-java


【解决方案1】:

试试看:

    var outputStream = new PipedOutputStream();
    var inputStream = new PipedInputStream(outputStream);

    var response =
            dockerClient.attachContainerCmd(container.getId())
                    .withLogs(false)
                    .withStdErr(true)
                    .withStdOut(true)
                    .withFollowStream(true)
                    .exec(new ResultCallback.Adapter<>() {
                        @Override
                        public void onNext(Frame object) {
                            System.out.println(object);  //for example
                            try {
                                outputStream.write(object.getPayload());
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    });

    try {
        response.awaitCompletion();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

变量 inputStream 将是您正在寻找的。 附言在我的情况下,我使用 Logs(false),因为它阻止了当前输出并且我只得到了日志的一部分。它可能与我正在连接的容器有关。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-08
    • 2021-06-06
    • 2020-06-24
    • 2019-05-05
    • 1970-01-01
    相关资源
    最近更新 更多