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?
Try to split your command in an array like structure. as an example below
Process process;
String[] commandAndArgs = new String[]{ "/bin/sh","docker","exec","-it","test_docker","java","-jar","test.jar" };
process = Runtime.getRuntime().exec(commandAndArgs);
set Environment and Working Directory both for your process. Since the error you are getting specifies Unknown Source , It can be ENVIRONMENT problem
java.lang.ProcessBuilder.start(Unknown Source)
From Java docs you can see it states this exec() overloaded method
exec(String[] cmdarray, String[] envp, File dir)
Executes the specified command and arguments in a separate process with the specified environment and working directory.
In case nothing stated works, I request you to kindly write a shell script file for your command and then set it executable using
chmod 755 or chmod +x script.sh;
then try to run that. I hope it works
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
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.