'Running a bash command on the host machine from a docker container, and geting inconsistent results
I'm working on a react-node app that will run in a docker container. This app will be a GUI for a lot of Virtual Machines set up for employees at my company, so the goal is that it needs to be able to run without configuring anything in the host machine.Just install the docker container and run it.
The problem is that I need to execute commands on the host machine from the docker container, and get there output. So i tried this SSH method:
import exec from 'ssh-exec';
function streamToString(stream) {
const chunks = [];
return new Promise((resolve, reject) => {
stream.on('data', (chunk) => {
console.log(Buffer.from(chunk))
chunks.push(Buffer.from(chunk))
});
stream.on('error', (err) => reject(err));
stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
})
}
async function runCommand(command) {
try {
const res = await streamToString(
exec(command, {
user: 'user',
host: IP_ADRESS,
password: 'password'
})
);
return res;
} catch (error) {
console.log(error);
}
}
,but sometimes it works, sometimes it just sends an empty string, and it also takes a lot longer than i thought it would.
** Is there anything wrong with my code here? Or is the method itself wrong? **
Example use:
const result = await runCommand(`git --git-dir=${path}/.git rev-parse --abbrev-ref HEAD`}
Example of the issue:
app.get("/testing", async (req, res) => {
console.log(await runCommand('echo test1'))
console.log(await runCommand('echo test2'))
console.log(await runCommand('echo test3'))
console.log(await runCommand('echo test4'))
console.log(await runCommand('echo test5'))
res.end("test ended");
})
Output:
Example app listening at http://localhost:3006
test2
test5
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
