You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kubernetes环境下Socket.IO轮询正常但WebSocket连接失败问题求助

Kubernetes环境下Socket.IO轮询正常但WebSocket连接失败问题求助

大家好,我最近在给Kubernetes上部署的Web应用加WebSocket功能,遇到了个棘手的问题,想请各位帮忙看看:

我的技术栈是用Python FastAPI做后端,Next.js做前端,通过fastapi-socketio和socketio实现WebSocket通信。

相关代码

前端代码(部署到K8s时已将协议改为wss):

const socket = io('ws://localhost:8000', {
  path: "/ws",
  transports: ['websocket'],
  retries: 1,
  reconnection: false,
});

后端MySocketClass.py:

from fastapi_socketio import SocketManager

class MySocketManager:
    sm_clients = {}
    def __init__(self, app, mount_route):
        # 这里cors_allowed_origin设为空数组,是因为已经在app.py里用FastAPI推荐的方式允许了所有跨域来源,重复设置会导致多header错误
        self.sm = SocketManager(app=app, mount_location=mount_route, socketio_path="", cors_allowed_origin=[])

后端app.py:

from fastapi import FastAPI

app = FastAPI()

@app.on_event("startup")
async def startup_event():
    app.state.socketClass = MySocketManager(app=app, mount_route="/ws")

问题现象

  • 本地开发环境下,WebSocket连接能正常建立,通信完全没问题
  • 部署到Kubernetes后,WebSocket连接直接失败,报错connection failed
  • 但如果把前端的传输方式改成polling,在K8s环境下就能正常工作

已尝试的解决方法

  • 配置了Ingress的各种推荐注解和相关配置,没有效果
  • 把后端Service改成NodePort进行调试,不管是本地前端连NodePort还是ClusterIP,后端都看不到任何WebSocket连接的请求日志
  • 按照Socket.IO文档的要求,降级了前后端的库版本,确保版本匹配,还是没用

有没有大佬能指点一下,这个问题可能出在哪里?应该怎么排查和解决?

备注:内容来源于stack exchange,提问作者ShaZar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.21 15:14:54