首页 > 解决方案 > Geth websocket over nginx 反向代理

问题描述

我尝试使用 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 配置有问题。

标签: nginxblockchainethereumweb3jsgeth

解决方案


正如评论中所说,要使用带有 SSL 的 websocket,您需要前缀 wss://。


推荐阅读