Docker Websocket Attaching in NodejS

2019-09-02 10:52发布

问题:

I want to connect to Docker API with Websockets, however, in any container it just gives me 403 Forbidden Error. I do not know what I am doing wrong, there is not enough documentation about it, but here is my code:

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);
    }
});

The output it produces is:

Container ceeef5eb34acf06dad7d6fea01dd71d9b0283c63b14bc52d49585aa379ec4922 created

error [Error: unexpected server response (403)]

But I see the Docker daemon output as follows:

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)

As it can be seen requests comes to Daemon but there is no indication why it gives a 403 Forbidden error.

回答1:

It seems that I needed to change 127.0.0.1 to localhost and it magically worked.