I want to send some java code as a string to an API to then run it in a docker container and return the console output, I have managed to do it with Python but as java first needs to be compiled then ran I'm unsure how to implement the language.
currently using the python image but I am not too familiar with java and im unsure how to approach it.
my environment is node using typescript and im using the dockerode module.
let container = await docker.createContainer({
Image: 'python',
Tty: true,
Cmd: ['/bin/bash'],
StdinOnce: true
});
I'm able to pass the string directly to the container by adding it to the Cmd after running python but not sure how I would pass a string into a file then compile and run it.
var options = {
Cmd: ['python', '-c'],
AttachStdout: true,
AttachStderr: true,
};
options.Cmd.push(code);
let exec = await container.exec(options);
I just have a listener to capture the output stream which can be used for later
stdout.on('data', (chunk: any) => {
let data = chunk.toString('utf8').split(/\r?\n/).filter((str: string) => {return str.length});
output = data;
})
any advice on which image to use along with how to pass the code through to get the output would be appreciated.
Depending on what you're trying to achieve, you may want to compile your code inside the docker container or not, or bind mount or push the files into the container.
This example simply mounts (binds) the current working directory inside the container and calls javac
(or java
). The resulting .class
file would appear in your current directory (only works on systems where your terminal is on the host). You could then re-run the same command with java
and the class name to execute it.
docker.run(
'java:8',
['javac', 'yourclass.java'],
process.stdout,
{
HostConfig: {
AutoRemove: true,
Binds: [
`${process.cwd()}:/app`
]
},
WorkingDir: '/app'
}
)
Your question says that you "want to send some java code as a string to an API", although exactly what qualifies as "sending a string to an API" is not clear. Along the lines of what you did with Python, you could echo '${code}' > myclass.java
, although you risk running into escaping issues with the quotation marks.
An alternative approach is to create the container and then container.putArchive('yourclass.java', options)
. I don't know if this qualifies as "sending a string".