I want to open up a docker container in a java file. Below is my code. I am able to open up the docker container with list but now want to run several commands within the docker container. I have an OutputStream which should pick up the data that I give in the java program. Maybe I am incorrectly understanding how to do this. Do I need to use another process for additional commands or can I construct more commands and give them to Output stream in a Byte array? I have also tried using the Runtime class which I believe is now depricated. See related posts here, how to run a command at terminal from java program?
Execute several line commands in a Java Programm
try {
List<String> list = new ArrayList<String>();
list.add("sudo");
list.add("docker");
list.add("exec");
list.add("-it");
list.add("sawtooth-shell-default");
list.add("bash");
ProcessBuilder pb = new ProcessBuilder(list);
pb.inheritIO();
Process process = pb.start();
process.waitFor();
OutputStream out = process.getOutputStream();
byte[] byteArr= {'l','s'};
out.write(byteArr);
out.flush();
} catch (Exception e) {
throw new RuntimeException(e);
}
I have also tried using && between my commands but I end up with a no such file or directory exeception. I add them to list like so,
list.add("&&");
list.add("ls");
Note from the second link I shared that I cannot combine my command into one big string. In that situation I think I would have to add the terminal name that I am using so in this case gnome-terminal but when I run with this string,
String command = "gnome-terminal sudo docker ... etc"
It also returns a no such file or directory error.
I have also tried putting
list.add("bash");
list.add("-c");
before the rest of my commands like this post suggests. Java ProcessBuilder to start execute multiple commands sequentially in Linux
Edit: I decided to change the name of this question. I realize that the problem is the additional commands are running outside of the docker contatiner. How can I run a command to bring up a docker contatiner and then inside the docker container run additional commands?
dockercommand at all comes with the ability to very easily root the host. Can you set up your application container to do the work it needs to on its own, without doing Docker-specific work in a separate privileged process?