java - 如何从java程序运行docker镜像?

标签 java shell docker ubuntu dockerfile

我正在尝试使用脚本从 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 文件中创建文件并且它有效。

最佳答案

您没有捕获流程中的任何错误消息或正常输出。也许它只是有效?

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

关于java - 如何从java程序运行docker镜像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59727265/

相关文章:

linux - Shell:bash 3.2.57 到 4.3.41 在 read -t 选项中的区别?

node.js - 创建自定义 Docker 镜像

适用于 Mac 的 Docker : Host network and port publishing

linux - 是否可以在 Kubernetes Pod 中挂载主目录 (~)?

java - 返回按钮和取消按钮的实现有什么区别?

java - 如何搜索javadoc生成的HTML文档?

java - 如何将 java.util.Date 转换为 GMT 格式

bash - 如何在 Bash 中查找变量是否为空

java - 将日期从 YYYY-MM-DD 转换为 YYYY-MM-DDTHH :mm:ssZ

shell - 如何将命令行参数传递给 shell 别名?