Docker and Node

Docker is a great tool and two different libraries and can make management very easy. The following two tools make working with Docker and node seemless.

dockerode

https://github.com/apocas/dockerode

Dockerode is a great tool for working with Docker in node. Below are some common things used.

listing, stopping and removing all containers

1
2
3
4
5
6
7
8
docker.listContainers(function (err, containers) {
  containers.forEach(function (cont) {
    var container = docker.getContainer(cont.Id);
    container.stop(function(){
      container.remove(cb);
    });
  });
});

Bind volume:

1
container.defaultOptions.attach.Binds = ['/var:/input:ro'];

Attaching to container:

1
2
3
container.attach(options, function handler(err, stream) {
  //do stuff
});

child_process

https://nodejs.org/api/child_process.html

child_process can manage docker pretty well in node. Here are some examples.

Creating a container:

1
2
3
4
5
docker.createContainer({Image: 'ubuntu', Cmd: ['/bin/bash'], name: 'ubuntu-test'}, function (err, container) {
  container.start(function (err, data) {
    //do something with container
  });
});

Starting an attached container:

1
  var child = spawn('docker', ['run', '-it', '--dns', '8.8.8.8', '--volume='/var:/input', myTag,  '/bin/bash'], {detached: true, stdio: ['ignore']});

Breaking this down,

--dns at times you will find within a container a domain will not resolve. Setting this will fix the issue.

--volume maps host directory to container.

/bin/bash command to run entering container.

Capturing container data:

1
2
3
4
5
6
7
8
var memoryStream = new MemoryStream();
var result = '';
memoryStream.on('data', function(data) {
  result += data.toString();
});
container.attach(options, function handler(err, stream) {
  stream.pipe(memoryStream);
});

Next, Docker and Ruby.