如何通过Java程序执行docker命令 [英] how to execute docker commands through Java program
问题描述
除了调用Docker远程API之外,我还需要开发一个仅与Docker Linux Client(而非Docker守护程序)对话的程序.这是我的代码
Instead of calling Docker remote APIs, I need develop a program which just talks to Docker Linux Client (not Docker daemon). Here is my code
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",它将显示无法在非tty输入上启用tty模式",如果我使用"-i",则会收到流关闭异常.
I always get errors. If I use "-it", it will says "cannot enable tty mode on non tty input", if I use "-i", I will get a Stream Closed Exception.
有什么办法可以解决这个问题?
Is there any way to solve this problem?
推荐答案
要克服您遇到的错误,应使用"-i"而不是"-it". -t arg告诉docker分配一个伪tty.
To overcome the error you're facing, you should use "-i" instead of "-it". The -t arg tells docker to allocate a pseudo tty.
话虽如此,我同意弗洛里安(Florian),您应该使用docker remote api. https://docs.docker.com/engine/reference/api/docker_remote_api/
Having said that, I agree with Florian, you should use the docker remote api. https://docs.docker.com/engine/reference/api/docker_remote_api/
这篇关于如何通过Java程序执行docker命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!