我想通过Websockets连接到Docker API,但在任何容器中,它只会给我403 Forbidden Error。我不知道我做错了什么,没有足够的文档,但这是我的代码:
var docker = require('docker.io')({
socketPath: false,
host: "http://127.0.0.1",
port: "4500"
});
var WebSocket = require('ws');
var opts = {
"AttachStdin": true,
"AttachStdout": true,
"AttachStderr": true,
"Tty": true,
"OpenStdin": true,
"Cmd": [
"/bin/bash"
],
"Image": "ubuntu"
};
docker.containers.create(opts, function(err, result) {
if (!err) {
var containerId = result.Id;
console.log("Container", containerId, "created");
docker.containers.start(containerId, function(err, result) {
console.log(result);
var ws = new WebSocket('ws://127.0.0.1:4500/v1.7/containers/' + containerId + '/attach/ws?logs=1&stderr=1&stdout=1');
ws.on("open", function() {
console.log("ok, open");
});
ws.on("message", function(msg) {
console.log("msg", msg);
});
ws.on("error", function(msg) {
console.log("error", msg);
});
});
} else {
console.log(err);
}
});
它产生的输出是:
Container ceeef5eb34acf06dad7d6fea01dd71d9b0283c63b14bc52d49585aa379ec4922 created
error [Error: unexpected server response (403)]
但是我看到Docker守护进程的输出如下:
Local (127.0.0.1) DNS resolver found in resolv.conf and containers can't use it. Using default external servers : [8.8.8.8 8.8.4.4]
[/var/lib/docker|f99d0d11] -job create() = OK (0)
2014/04/16 23:04:09 POST http://127.0.0.1:4500/v1.7/containers/ceeef5eb34acf06dad7d6fea01dd71d9b0283c63b14bc52d49585aa379ec4922/start
[error] common.go:41 Error parsing media type: error: mime: no media type
[/var/lib/docker|f99d0d11] +job start(ceeef5eb34acf06dad7d6fea01dd71d9b0283c63b14bc52d49585aa379ec4922)
[/var/lib/docker|f99d0d11] +job allocate_interface(ceeef5eb34acf06dad7d6fea01dd71d9b0283c63b14bc52d49585aa379ec4922)
[/var/lib/docker|f99d0d11] -job allocate_interface(ceeef5eb34acf06dad7d6fea01dd71d9b0283c63b14bc52d49585aa379ec4922) = OK (0)
[/var/lib/docker|f99d0d11] -job start(ceeef5eb34acf06dad7d6fea01dd71d9b0283c63b14bc52d49585aa379ec4922) = OK (0)
2014/04/16 23:04:09 GET /v1.7/containers/ceeef5eb34acf06dad7d6fea01dd71d9b0283c63b14bc52d49585aa379ec4922/attach/ws
[/var/lib/docker|f99d0d11] +job inspect(ceeef5eb34acf06dad7d6fea01dd71d9b0283c63b14bc52d49585aa379ec4922, container)
[/var/lib/docker|f99d0d11] -job inspect(ceeef5eb34acf06dad7d6fea01dd71d9b0283c63b14bc52d49585aa379ec4922, container) = OK (0)
可以看出,Daemon收到了请求,但没有迹象表明它为什么会出现403 Forbidden错误。
我似乎需要将127.0.0.1
更改为localhost
,它神奇地起了作用。