简体   繁体   中英

Sending 'exec' commands to Docker container using Java

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();
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM