10

Is there any better way to execute docker commands from a node js apart from using shelljs(similar packages) to execute those commands?

I have seen the package dockerode. Though it is great for some commands, it doesn't give much view on 'docker exec' command.

I just need more control while executing docker exec from nodejs which shelljs fail to provide. I want to know once the docker exec command has been executed whether it got executed successfully or not.

Nithin D J
  • 299
  • 1
  • 2
  • 12

4 Answers4

3

If you want to have run the command from nodejs script, use shelljs or child process to run the command and redirect the output it into a log or txt file. And the use function something like this saerch for error string in the file.

What basically happens is when you execute a docker exec within a cli, even though the error occurs that doesn't captured by shelljs. So the exit code will be 0 either way. So this causes difference in catching error in normal shell command and docker exec command.

We could make use dockerode npm package. We can use this particular example and write it as per our use case. I just changed the code listen to the event 'data' and 'end' on the stream that returned.

Nithin D J
  • 299
  • 1
  • 2
  • 12
  • Looks like he is asking for npm module. not the way to execute shell commands from nodejs – Amit Sharma Aug 25 '19 at 15:40
  • As it turns out, for many use cases, dockerode doesn't perform as well as shelljs. For example, dockerode's 'docker run' is not the same as a real 'docker run' but is a 'docker container create' followed by a 'docker container start', and some docker containers which are geared towards only working with docker run will not function with dockerode. Thus, suggesting shelljs is a valid solution. – Nitin Khanna Jan 28 '20 at 09:42
3

You can use the docker-compose npm instead: https://www.npmjs.com/package/docker-compose

2

You can use child_process for the exec bash commands and get results to see success or not.

S.Polat
  • 71
  • 8
  • As I am running the docker exec in detached mode, I am not getting the result in shelljs. I think the same will happen f I use child_process. So is there any way to do that? I am using in detached mode because after one command execution the cli will get hang and will not execute the next commands as docker exec is inconsistent. – Nithin D J May 21 '18 at 03:25
1

You can use child process for running docker commands from node js. For example

var sys = require('sys')
var exec = require('child_process').exec;

function puts(error, stdout, stderr) { sys.puts(stdout) }
exec("ls -la", function(err, stdout, stderr) {
  console.log(stdout);
});
Rubin bhandari
  • 1,873
  • 15
  • 20