Search code examples
javadockerprocessbuilderruntime.exec

How do I call docker container using java commandline?


I'm trying to run docker container from inside a java application.

Code

String[] command = {"docker exec -it test_docker java -jar test.jar"};
ProcessBuilder pb = new ProcessBuilder(command);
pb.inheritIO();
Process proc = pb.start();

While running the code I am getting an error,

Exception in thread "main" java.io.IOException: Cannot run program "docker exec -it test_docker java -jar test.jar": CreateProcess error=2, The system cannot find the file specified
        at java.lang.ProcessBuilder.start(Unknown Source)
        at com.test.company.test.RunTask.main(RunTask.java:79)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
        at java.lang.ProcessImpl.create(Native Method)
        at java.lang.ProcessImpl.<init>(Unknown Source)
        at java.lang.ProcessImpl.start(Unknown Source)
        ... 2 more

Here is my container list,

$ docker ps
CONTAINER ID        IMAGE                          COMMAND                  CREATED             STATUS              PORTS                                            NAMES
f37c7ae71e12        tomcat:latest                  "/usr/local/tomcat/b"   2 hours ago         Up 2 hours          0.0.0.0:8080->8080/tcp                           tomcat_docker
f2cc2579b861        java:latest                    "/bin/bash"              2 hours ago         Up 2 hours          0.0.0.0:2377->2377/tcp                           test_docker
673c6617a0d5        mysql                          "docker-entrypoint.s"   2 hours ago         Up 2 hours          0.0.0.0:53306->3306/tcp                          mysql_docker
a76ca8d8f9e4        java:latest                    "/bin/bash"              2 hours ago         Up 2 hours                                                           Client

is it possible to run docker container command using java? If possible then how do I execute using java?


Solution

  • I have found the way through which you can run docker command inside java. There is a library available named spotify/docker-client on git docker-client using that you can run your docker command using java.It's easy to use library.

    Here is a user manual docker-client user_manual