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) ... }
Dockerfile:
FROM golang:1.11.4-alpine3.8 ... (Build and expose port commands) ...
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) ...
Additional Information:
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!