Skip to content

Instantly share code, notes, and snippets.

@caltuntas
Created November 5, 2024 07:13
Show Gist options
  • Save caltuntas/a7bd4752e49a59eb8bb6eeecf6bfffa1 to your computer and use it in GitHub Desktop.
Save caltuntas/a7bd4752e49a59eb8bb6eeecf6bfffa1 to your computer and use it in GitHub Desktop.
nginx-websocket-sticky
version: '3.7'
services:
websocket-server:
image: websocket-server
deploy:
replicas: 3
update_config:
parallelism: 2
delay: 10s
networks:
- webnet
nginx:
image: nginx:1.22
ports:
- "80:80"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
networks:
- webnet
networks:
webnet:
FROM golang:1.23-alpine
WORKDIR /app
COPY go.mod .
COPY . .
RUN go mod download
RUN go build -o websocket-server .
EXPOSE 8080
CMD ["./websocket-server"]
module websocket
go 1.23
require github.com/gorilla/websocket v1.5.3
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
// Copyright 2015 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"flag"
"fmt"
"html/template"
"log"
"math/rand"
"net/http"
"github.com/gorilla/websocket"
)
var addr = flag.String("addr", "0.0.0.0:8080", "http service address")
var upgrader = websocket.Upgrader{} // use default options
var num = rand.Int()
func echo(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
defer c.Close()
for {
mt, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
break
}
log.Printf("recv: %s", message)
newMessage := fmt.Sprintf("%s from %d", message, num)
err = c.WriteMessage(mt, []byte(newMessage))
if err != nil {
log.Println("write:", err)
break
}
}
}
func home(w http.ResponseWriter, r *http.Request) {
homeTemplate.Execute(w, "ws://"+r.Host+"/echo")
}
func main() {
flag.Parse()
log.SetFlags(0)
http.HandleFunc("/echo", echo)
http.HandleFunc("/", home)
log.Fatal(http.ListenAndServe(*addr, nil))
}
var homeTemplate = template.Must(template.New("").Parse(`
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
window.addEventListener("load", function(evt) {
var output = document.getElementById("output");
var input = document.getElementById("input");
var ws;
var print = function(message) {
var d = document.createElement("div");
d.textContent = message;
output.appendChild(d);
output.scroll(0, output.scrollHeight);
};
document.getElementById("open").onclick = function(evt) {
if (ws) {
return false;
}
ws = new WebSocket("{{.}}");
ws.onopen = function(evt) {
print("OPEN");
}
ws.onclose = function(evt) {
print("CLOSE");
ws = null;
}
ws.onmessage = function(evt) {
print("RESPONSE: " + evt.data);
}
ws.onerror = function(evt) {
print("ERROR: " + evt.data);
}
return false;
};
document.getElementById("send").onclick = function(evt) {
if (!ws) {
return false;
}
print("SEND: " + input.value);
ws.send(input.value);
return false;
};
document.getElementById("close").onclick = function(evt) {
if (!ws) {
return false;
}
ws.close();
return false;
};
});
</script>
</head>
<body>
<table>
<tr><td valign="top" width="50%">
<p>Click "Open" to create a connection to the server,
"Send" to send a message to the server and "Close" to close the connection.
You can change the message and send multiple times.
<p>
<form>
<button id="open">Open</button>
<button id="close">Close</button>
<p><input id="input" type="text" value="Hello world!">
<button id="send">Send</button>
</form>
</td><td valign="top" width="50%">
<div id="output" style="max-height: 70vh;overflow-y: scroll;"></div>
</td></tr></table>
</body>
</html>
`))
events {}
http {
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 80;
server_name your_domain.com; # Replace with your domain
location /echo {
proxy_pass http://websocket-server:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_read_timeout 86400; # Set a long timeout
}
}
}
docker network create websocket-network
docker run -d --name websocket-server --network websocket-network websocket-server
docker run -d -p 80:80 --name nginx \
-v $(pwd)/nginx.conf:/etc/nginx/nginx.conf \
--network websocket-network \
nginx:1.22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment