My question is very similar to this post. I am trying to access a socket server with NGINX ingress in minikube. I am not sure if different annotations are still necessary for cluster v1.22.2, as described here, but I tried adding them as described in various stackoverflow posts and attempted this and this, but none worked for me.
Although it works fine when I forward the service port, I am getting error when I am trying to access it with ingress.
*WebSocket connection to 'ws://textchess.com/socket.io/?EIO=4&transport=websocket' failed:*
The driver\etc\host file has minikube's ip as textchess.com
index.js
const express = require("express");
const { createServer } = require("http");
const { Server } = require("socket.io");
const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
cors: {
origin: "*",
methods: ["GET", "POST"],
},
});
io.on("connection", (socket) => {
console.log("connection established");
socket.on("client_emit", (arg) => {
socket.emit("server_emit", arg);
});
});
httpServer.listen(3000);
Deployment/ClusterIP service
apiVersion: apps/v1
kind: Deployment
metadata:
name: socket-deployment
labels:
app: socket
spec:
replicas: 1
selector:
matchLabels:
app: socket
template:
metadata:
labels:
app: socket
spec:
containers:
- name: socket
image: socket
---
# clusterIP service
apiVersion: v1
kind: Service
metadata:
name: socket-srvc
spec:
type: ClusterIP
selector:
app: socket
ports:
- name: socket-port
protocol: TCP
port: 3000
targetPort: 3000
ingress
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: ingress-test
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
nginx.ingress.kubernetes.io/use-regex: "true"
nginx.org/websocket-services: "socket-srvc"
spec:
rules:
- host: textchess.com
http:
paths:
- path: /test
pathType: Prefix
backend:
service:
name: socket-srvc
port:
number: 3000
- path: /socket.io/.*
pathType: Prefix
backend:
service:
name: socket-srvc
port:
number: 3000
ingressClassName: nginx
---
apiVersion: networking.k8s.io/v1
kind: IngressClass
metadata:
name: nginx
spec:
controller: k8s.io/ingress-nginx
client
<script>
// const socket = io("http://localhost:3000", { transports: ["websocket"] });
const socket = io("http://textchess.com:/test", {
reconnection: true,
transports: ["websocket"],
});
socket.on("server_emit", (args) => {
console.log(args);
});
document.getElementById("event_emitter").onclick = function changeContent() {
var d = new Date();
var time = d.toLocaleTimeString();
socket.emit("client_emit", time);
};
</script>