简体   繁体   中英

How to create and start a container through docker API

I have been playing around with docker and starting containers through scripts but wanted to try out docker api and decided to try dockerode.

Now, i cannot manage to bind the host machine IP to the container created. How would i send the following command to the Docker API in json format through a http post?

docker run -p my.host.ip.address:80:80 --name www.blaha.com eugeneware/docker-wordpress-nginx 

i have read through docker api documentation several times and cannot find a way to pass the actual IP in the json post.

So, if I understand the question, you are looking for something like this....

var Docker = require("dockerode");
var fs = require("fs");
var PropertiesReader = require('properties-reader');

var properties = PropertiesReader('docker.properties');


var dockerHost = properties.get('DOCKER_HOST');  //'http://docker';
var dockerPort = properties.get('DOCKER_PORT')   //2375;
var dockerImage = properties.get('DOCKER_IMAGE');

console.log("docker host/port =  " + dockerHost + ":" + dockerPort);

var docker = new Docker({
   host: dockerHost,
   port: dockerPort
});

module.exports.CreateContainer = function(user_id, cb) {
   var name = 'docker-test-' + user_id;
   console.log("Create container: " + name);
   docker.createContainer({
         Image: dockerImage,
         name: name,
         ExposedPorts: {"8080/tcp": {} }
      },
      function (err, container) {
      if (err)
         throw (err);
      container.start({PortBindings: {"8080/tcp": [{ "HostPort": ""}] } }, function (err, data) {
         if (err)
            throw (err);
         console.log("Starting container");
         container.inspect(function (err, data) {
            if (err)
               throw (err);
            cb(dockerHost + ":" + data.NetworkSettings.Ports['8080/tcp'][0].HostPort);
        });
      });
   });
}

This is a module I call from a nginx webserver. The main function is invoked from another .js file via:

Docker.CreateContainer(user_id, function(hostInfo) {
            console.log("Retrieved hostinfo: " + hostInfo);
            res.json("Docker initalized on server: " + hostInfo);
         });

As you see, I reference the port quiet a few times. Not sure I really need to do that, but it works. Firstly, I create the container from an image, then I start it. Lastly, I inspect the container to return details to the caller.

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM