Cannot bind to localhost
jaredonline opened this issue · comments
Howdy!
I'm trying to run a websocket server inside a Docker container, and I think that means I have to bind my server to localhost.
Outside of docker, if I use
let bind = "127.0.0.1:2794";
let server = Server::bind(bind).unwrap();
and start my server with just cargo run
, I'm able to open a connection to it through the Firefox console with:
s = new WebSocket("ws://127.0.0.1:2794", ["rust-websocket"]);
and with
s = new WebSocket("ws://localhost:2794", ["rust-websocket"]);
If I change the bind in my Rust to
let bind = "localhost:2794";
let server = Server::bind(bind).unwrap();
both of those connections will fail in Firefox with an error:
Firefox can’t establish a connection to the server at ws://localhost:2794/.
If I use the 127.0.0.1
binding from within Docker, it doesn't seem to work. I'm not super great with networking in general, or with Docker's networking, but my reference is that the default nginx image (which is working fine) is binding to localhost
and not 127.0.0.1
.
127.0.0.1
(localhost
) is typically inside Docker container, not shared between host and container.
If it's Linux, try --network=host
to turn off network virtualisation and make container's localhost the real localhost.
Alternative 1: Use non-localhost address for websocket. For example, bind to to 0.0.0.0 and forward the port using Docker configuration -p 2794:2794
.
Alternative 2: If Nginx is available and exposed, you can reuse Nginx's HTTP (HTTPS) port and forward some URIs it to your websocket server:
location /ws {
proxy_read_timeout 1d;
proxy_send_timeout 1d;
proxy_pass http://localhost:2794;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
Binding to 0.0.0.0
worked. Thank you!