I'm having trouble with putting my WebSocket server in a Docker container.
This is the server code, which writes to a new connection with "connected".
// server.go
func RootHandler(w http.ResponseWriter, r *http.Request) {
upgrader := websocket.Upgrader{ // (Uses gorilla/websocket)
ReadBufferSize: 4096,
WriteBufferSize: 4096,
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
panic(err)
}
if err = conn.WriteMessage(websocket.TextMessage, []byte("connected")); err != nil {
panic(err)
}
}
func main() {
fmt.Println("server is running")
// For graceful shutdown
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
server := http.Server{Addr: "localhost:8000"}
defer server.Close()
http.HandleFunc("/", RootHandler)
go func() {
err := server.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
panic(err)
}
}()
<-stop
}
Here is the client:
// client.go
func main() {
connection, _, err := websocket.DefaultDialer.Dial("ws://localhost:8000", nil)
if err != nil {
panic(err)
}
_, b, err := connection.ReadMessage()
if err != nil {
panic(err)
}
fmt.Println(string(b)) // "connected"
}
Running server.go
then client.go
prints "connected", showing that the code is working. Now I want to put the server in a Docker container. This is dockerfile
:
FROM golang:1.11.4-alpine3.8
COPY . $GOPATH/src/websocket-test
WORKDIR $GOPATH/src/websocket-test
RUN ["go", "build", "server.go"]
EXPOSE 8000
CMD ["./server"]
I use these commands to build and start the container, exposing 8000/tcp.
docker build -t websocket-test .
docker run -p 8000:8000 websocket-test
I can confirm that the server is running because it prints "server is running". If I start client.go
outside the container, it panics:
panic: read tcp [::1]:60328->[::1]:8000: read: connection reset by peer
What I expect is the same outcome as before—printing "connected" on the client side. The error message means that the server dropped the connection before the handshake. I don't understand the "60328" number. As far as I know, WebSocket doesn't change ports on upgrade, so I should be okay with exposing just 8000.
I do not know what I must change to be able to connect via WebSocket to my server.