How to manage docker containers using nodejs

mobyjs

Just a little snippet about the dockerode module, which exposes an API to manage docker via nodejs.

It makes docker automation really easy using javascript.

For example, here is how to list all containers running on a host, and create a container.

var q = require('q');
var config = require('config');
var dockerode = require('dockerode');
var api = new dockerode({ socketPath: config.get('docker.socket_path') });

var docker = {};

/** Lists all containers running on this host */
docker.listAll = function() {
    var def = q.defer();
    api.listContainers(function (err, containers) {
        if (err) throw err;
        var ret = [];
        // Get the id for each container un the received array of containers
        containers.forEach(function (it) {
           ret.push(it.Id);
        });
        def.resolve(ret);
    });
    return def.promise;
};

/** Create a httpd container on this host */
docker.createContainer = function(task) {
    var def = q.defer();
  console.log('creating container ...');
  api.createContainer({
    Image: 'httpd'
  }, function(err, container) {
    if (err) throw err;
    console.log('container created ' + JSON.stringify(container));
    container.start(function (err, data) {
        if (err) throw err;
        def.resolve(container);
    });
  });
  return def.promise;
};

module.exports = docker;

 

Stephen B

Développeur informatique passionné de numérique et de technologie au sens large du terme.