通过Nginx反向代理的Geth Websocket

时间:2019-02-02 10:08:48

标签: nginx blockchain ethereum web3js geth

我尝试使用nginx作为反向代理通过websocket连接到我的私有geth区块链。这是我的设置:

节点设置:

docker run                                                                  
    -d
    --net                       mynet
    --ip                        192.168.1.21
    -v                          myvol:/root
    ethereum/client-go:stable
        --datadir               "/root/geth1"                              
        --networkid             1029
        --syncmode              "full"

        --ws                                                              
        --wsaddr                "0.0.0.0"                                  
        --wsport                8546                                       
        --wsapi                 "eth,net,web3,rpc"                         
        --wsorigins="*"                                                            

        --bootnodes             $BOOTNODE                                  
        --port                  30303                                      
        --maxpeers              8                                          
        --nat                   "any"

Nginx配置:

server {
    #listen     80;
    listen      443 ssl http2 default_server;
    listen [::]:443 ssl http2 default_server ipv6only=on;

    server_name             mydomain.de;

    # basic auth stuff here
    # ssl stuff here

    location /mynode {

        if ($request_method = OPTIONS) {
            return 204;
        }

        auth_basic          off;

        add_header          Access-Control-Allow-Origin  "$http_origin";
        add_header          Access-Control-Allow-Headers "authorization, content-type";
        add_header          Access-Control-Allow-Methods "DELETE, GET, OPTIONS, POST, PUT, UPDATE";

        # to avoid double origin value what leads to an CORS error in the browser
        proxy_hide_header   Access-Control-Allow-Origin;

        proxy_set_header    Host                $host;
        proxy_set_header    X-Real-IP           $remote_addr;
        proxy_set_header    X-Forwarded-For     $proxy_add_x_forwarded_for;
        proxy_set_header    X-Forwarded-Proto   $scheme;

        proxy_http_version  1.1;
        proxy_set_header    Upgrade             $http_upgrade;
        proxy_set_header    Connection          "upgrade";

        proxy_pass          http://192.168.1.21:8546;
    }
}

web3.js:

const Web3 = require('web3');

const web3 = new Web3('ws://mydomain.de/mynode');

web3.eth.getAccounts()
    .then(console.log)
    .catch(console.log);

此配置不适用于websocket。在我将它与RPC配合使用之前,它确实可靠。

如果我将-p 8546:8456添加到我的节点并直接连接到该节点(const web3 = new Web3('ws://mydomain.de:8456')),那么一切都会正常进行。所以我想nginx配置有问题。

1 个答案:

答案 0 :(得分:0)

如评论中所述,要将Websocket与SSL配合使用,您需要在wss://前面加上前缀。