Why Can't I Connect to My WebSocket Server Inside a Docker Container from Outside?

Patricia Arquette
Release: 2024-11-06 13:29:03
Original
505 people have browsed it

Why Can't I Connect to My WebSocket Server Inside a Docker Container from Outside?

Troubleshooting Dockerization of a WebSocket Server

Issue:

Difficulty connecting to a WebSocket server running in a Docker container when accessing it from outside the container.

Server Code:

// server.go
func RootHandler(w http.ResponseWriter, r *http.Request) {
    ... (WebSocket handling code) ...
}
Copy after login

Dockerfile:

FROM golang:1.11.4-alpine3.8
... (Build and expose port commands) ...
Copy after login

Expected Behavior:

Connecting to the WebSocket server from outside the container should print "connected" on the client side.

Actual Error:

The client panics with the error: "panic: read tcp [::1]:60328->[::1]:8000: read: connection reset by peer."

Cause:

The server is listening on localhost (127.0.0.1) within the container, which is not accessible from outside the container.

Solution:

To resolve this issue, change the listen address of the server in server.go to ":8000" instead of "localhost:8000." This way, the server will listen on all IP addresses of the container.

// server.go
func RootHandler(w http.ResponseWriter, r *http.Request) {
    ... (WebSocket handling code) ...
}

// main()
server := http.Server{Addr: ":8000"}
... (Rest of server setup) ...
Copy after login

Additional Information:

  • Docker exposes ports by creating iptables rules to forward traffic to the container's IP address.
  • Docker containers typically get IP addresses within the docker0 network interface.
  • When connecting from outside the container, traffic is forwarded to the container's IP address, which may not match the listen address of the server.

The above is the detailed content of Why Can't I Connect to My WebSocket Server Inside a Docker Container from Outside?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!