如何通过Java程序执行docker命令
我不需要调用Docker远程API,而是需要开发一个与Docker Linux Client(不是Docker守护进程)对话的程序。 这是我的代码
try { String[] command = {"docker", "run", "-it", "tomcat:9", "bash"}; ProcessBuilder pb = new ProcessBuilder(command); pb.inheritIO(); Process proc = pb.start(); InputStream is = proc.getInputStream(); OutputStream os = proc.getOutputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os)); writer.write("pwd"); writer.flush(); String line = ""; while ((line = reader.readLine()) != null) { System.out.print(line + "\n"); } proc.waitFor(); } catch (Exception e) { e.printStackTrace(); }
我总是得到错误。 如果我使用“-it”,它会说“不能在非ttyinput上启用tty模式”,如果我使用“-i”,我将得到一个Stream Closed Exception。
有什么办法可以解决这个问题吗?
为了克服你面临的错误,你应该使用“-i”而不是“-it”。 -t arg告诉docker分配一个伪tty。
public void startContainer(String containerId) throws Exception { final DockerClient docker = DefaultDockerClient.builder() .uri(URI.create("https://192.168.64.3:2376")) .dockerCertificates(new DockerCertificates(Paths.get("/Users/d.romashov/.docker/machine/machines/dinghy"))) .build(); docker.startContainer(containerId); }