Home >Backend Development >Golang >How to Dockerize a WebSocket Server When Facing 'Connection Reset by Peer'?
You may encounter difficulty containerizing a WebSocket server in Docker. This article provides guidance on resolving this issue.
Scenario:
You have a WebSocket server code (server.go) and a client (client.go). Running these files outside the Docker container works without issues. However, after containerizing the server, connecting to it from outside the container results in an error:
panic: read tcp [::1]:60328->[::1]:8000: read: connection reset by peer
Cause:
The problem lies in the server listening address. By default, the server listens on localhost (127.0.0.1). This is fine when running outside the container, but inside the container, this address is not accessible.
Solution:
To resolve this, change the listen address to 0.0.0.0:8000, which instructs the server to listen on all its container's IP addresses.
server := http.Server{Addr: ":8000"}
Explanation:
By exposing a port in a Docker container (e.g., -p 8000:8000), Docker creates iptables rules to forward traffic to the container's IP address. By listening on 0.0.0.0:8000, the server ensures it accepts connections forwarded to its container's IP address.
The above is the detailed content of How to Dockerize a WebSocket Server When Facing 'Connection Reset by Peer'?. For more information, please follow other related articles on the PHP Chinese website!