How to execute docker commands using a Java program

Instead of calling the remote Docker APIs, I need to develop a program that just talks to the Docker Linux Client (and not the 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(); } 

I always get errors. If I use "-it", he will say: "It is not possible to enable tty mode on input without tty", if I use "-i", I will get a stream exception.

Is there any way to solve this problem?

+5
source share
3 answers

To overcome the error you encounter, you must use "-i" instead of "-it". -t arg tells the docker about the assignment of the pseudo-tty.

Having said that, I agree with Florian, you should use dockers remote api. https://docs.docker.com/engine/reference/api/docker_remote_api/

+3
source

You can use the docker client for java (e.g. https://github.com/spotify/docker-client ). Here is a usage example:

 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); } 
+1
source

I suggest you do not use any input or output stream, instead write the output in a file in the docker image. And read your file in your main Java program.

Hope this helps

0
source

All Articles