1

I'm trying to send docker commands using Java Runtime. Commands like docker cp works very nice with the below method as well as typing directly from the terminal.

  1. First problem is that the docker exec command works only from the terminal, not with the Java Runtime. Other docker commands like docker cp works as expected. The only problem is that I can't run commands on the container, like echoing on the container's terminal.

  2. Also the 2nd problem is that the System.out.println(...)method in the below method, doesn't actually print anything.

private static void runCommand() throws IOException, InterruptedException {
        Process proc = Runtime.getRuntime().exec(
                new String[]{"/bin/sh",
                        "-c",
                        "docker exec -u 0 -it <CONTAINER_NAME> echo",  "'abc'"});
        BufferedReader reader =
                new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String line = "";
        while ((line = reader.readLine()) != null) {
            System.out.print(line + "\n");
        }
        proc.waitFor();
}
Anil
  • 543
  • 3
  • 16
  • Does this answer your question? [how to execute docker commands through Java program](https://stackoverflow.com/questions/37810115/how-to-execute-docker-commands-through-java-program) – RamPrakash Jan 20 '20 at 21:24
  • Unfortunately not. I can already send docker commands, the problem is to send the commands that will be run inside the container with 'exec' command. – Anil Jan 20 '20 at 21:37
  • Would it not be better to use the API? https://github.com/docker-java/docker-java/wiki – hoipolloi Jan 20 '20 at 22:22
  • @Anil hello, did you resolved this? I am also trying to do something similar. I want to connect to wildfly container and do deployment disable. please let me know if you got it resolved. thanks – Dungeon_master Oct 28 '21 at 17:45

1 Answers1

1

There is no need to run docker inside a shell. You can start the process directly. As of Java 1.7 you can also use ProcessBuilder.inheritIO() to redirect the standard I/O of the subprocess

Below a working example that prints the output of the echo command:

ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("docker", "exec" , "-it", "<CONTAINER_NAME_OR_ID>", "echo", "abc").inheritIO();

try {
  Process process = processBuilder.start();
  BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

  String line;
  while ((line = reader.readLine()) != null) {
    System.out.println(line);
  }

  int exitCode = process.waitFor();
  System.out.println("\nExited with error code : " + exitCode);

} catch (Exception e) {
  e.printStackTrace();
} 

Hope this helps.

b0gusb
  • 4,283
  • 2
  • 14
  • 33