【问题标题】:How to run a docker image from java Program?如何从 java 程序运行 docker 映像?
【发布时间】:2020-04-30 19:04:19
【问题描述】:

我正在尝试使用脚本从 java 程序运行 Ubuntu 映像;方法如下:

我的java代码:

public static void main(String[] args) {
    executeCommand("/home/abrahem/IdeaProjects/untitled3/src/createContainer.sh");
}


public static void executeCommand(String filePath) {
    File file = new File(filePath);
    if (!file.isFile()) {
        throw new IllegalArgumentException("The file " + filePath + " does not exist");
    }
    try {
        if (isLinux()) {
            Process p = Runtime.getRuntime().exec("sh " + filePath);
            p.waitFor(); // i tried to remove this but still not work for my me 
        } else if (isWindows()) {
            Runtime.getRuntime().exec("cmd /c start " + filePath);
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

这是我的 createContainer.sh 脚本文件:

#!bin/sh
sudo docker run ubuntu 

当我转到bin 并输入:

docker ps

docker ps -a

它应该显示正在运行的 Ubuntu 容器,但它没有。

注意:shell位置没有问题;我尝试在 shell 文件中创建文件,它可以工作。

【问题讨论】:

  • 在 try 块中调试你的代码。
  • sudo docker run --name myubuntu -itd ubuntu 试试这个。
  • @RamPrakash 感谢您的评论,但如何?调试也不例外,我有尝试块。
  • @TaraPrasadGurung 我试过了,但仍然不适合我
  • 您可以尝试按照本教程:baeldung.com/run-shell-command-in-java 从您运行的程序中获取输出。

标签: java shell docker ubuntu dockerfile


【解决方案1】:

您不会从您的流程中捕获任何错误消息或正常输出。也许它只是工作?

使用 Process 的 getErrorStream() 和 getOutputStream() 方法来捕获进程的输出,有点像 here 中描述的那样。您可能只会看到预期的输出。如果不是,它应该是错误流上的错误消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多