AWS Kubernetes Ingress nginx websocket 代理

在需要配置WebSocket的Ingress服务上增加下面注解

metadata:
  annotations:
    nginx.org/websocket-services: "SERVICE_NAME"

WebSocket 测试 ws-test.yaml,注意看Ingress部分配置

apiVersion: v1
kind: Pod
metadata:
  name: ws
  labels:
    app: ws
spec:
  containers:
  - name: ws
    image: cliven/ws-loop:v1
    ports:
    - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: ws
spec:
  ports:
  - port: 80
    protocol: TCP
    targetPort: 80
  selector:
    app: ws
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ws
  annotations:
    nginx.org/websocket-services: "ws"
spec:
  rules:
  - host: your.domain.com
    http:
      paths:
      - path: /ws
        backend:
          serviceName: ws
          servicePort: 80

需要自己设置一下本机的 hosts文件 将这个域名指向对应集群的地址或IP

运行服务端测试程序

docker run -p 80:80 cliven/ws-loop:v1

测试页面


<pre id="log">pre>
<script>
  const SERVER_URL = 'ws://your.domain.com/ws'
  // helper function: log message to screen
  function log(msg) {
    document.getElementById('log').textContent += msg + '\n';
  }

  // setup websocket with callbacks
  var ws = new WebSocket(SERVER_URL);
  ws.onopen = function() {
    log('CONNECT');
  };
  ws.onclose = function() {
    log('DISCONNECT');
  };
  ws.onmessage = function(event) {
    log('MESSAGE: ' + event.data);
  };
script>

打开页面,依次输出 1-10,然后断开连接
AWS Kubernetes Ingress nginx websocket 代理_第1张图片

这种配置只影响到一个服务。

参考

[1]. nginx . inc . examples . WebSocket support . https://github.com/nginxinc/kubernetes-ingress/tree/master/examples/websocket
[2]. websocketd . github . README . https://github.com/joewalnes/websocketd/
[3]. Nginx dropping Connect/Upgrade headers for WebSocket handshake . timdorr . github . https://github.com/kubernetes/ingress-nginx/issues/3746

你可能感兴趣的:(AWS,Kubernetes)