所以,如果我理解这个问题,你正在寻找这样的东西......
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);
});
});
});
}
这是我从 nginx 网络服务器调用的模块。main 函数通过以下方式从另一个 .js 文件调用:
Docker.CreateContainer(user_id, function(hostInfo) {
console.log("Retrieved hostinfo: " + hostInfo);
res.json("Docker initalized on server: " + hostInfo);
});
如您所见,我多次引用端口安静。不确定我是否真的需要这样做,但它确实有效。首先,我从图像创建容器,然后启动它。最后,我检查容器以将详细信息返回给调用者。
我希望这有帮助。