我尝试使用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 config:
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配置有问题。
如评论中所述,要使用带有 SSL 的 websocket,您需要在 wss://上添加前缀。