JupyterHub环境下Kernel连接失败及WebSocket报错问题求助
环境信息
系统与Python版本
- Ubuntu 22.04
- Python 3.10.6
已安装的相关包
pip3 list | grep 'jupyter' jupyter 1.0.0 jupyter_client 8.6.2 jupyter-console 6.6.3 jupyter_core 5.7.2 jupyter-events 0.10.0 jupyter-lsp 2.2.5 jupyter_server 2.14.1 jupyter_server_terminals 0.5.3 jupyter-telemetry 0.1.0 jupyterhub 5.0.0 jupyterlab 4.2.2 jupyterlab_pygments 0.3.0 jupyterlab_server 2.27.2 jupyterlab_widgets 3.0.11 pip3 list | grep 'notebook' notebook 7.2.1 notebook_shim 0.2.4 pip3 list | grep 'tornado' tornado 6.4.1 pip3 list | grep 'ipykernel' ipykernel 6.7.0
JupyterHub配置
jupyterhub_config.py内容:
c.JupyterHub.bind_url = 'http://:8888/jhub/'
启动命令
/usr/bin/python3 /usr/local/bin/jupyterhub -f /etc/jupyterhub/jupyterhub_config.py
问题现象
- 可通过
https://domain_test.com/jhub登录JupyterLab仪表板 - 界面始终显示“Kernel is disconnected”,无法用
shift + Enter执行代码 - Chrome开发者控制台反复报错:WebSocket连接到
wss://domain_test.com/jhub/user/test_user/api/kernels/xxx/channels?session_id=xxx失败,持续尝试重连
排查方案
1. 反向代理配置问题(优先级最高)
你通过HTTPS访问,但JupyterHub绑定的是HTTP,中间的反向代理(如Nginx)未正确配置WebSocket转发规则,这是此类问题的常见原因:
- 确保代理配置中包含WebSocket升级相关的头信息,示例Nginx配置:
location /jhub/ { proxy_pass http://localhost:8888/jhub/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; # WebSocket 必需配置 proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_read_timeout 86400; } - 确认代理已正确传递
X-Forwarded-Proto头,JupyterHub需要识别外部使用的是HTTPS,否则会生成错误的WebSocket地址。
2. 补充JupyterHub环境识别配置
在jupyterhub_config.py中添加以下配置,让JupyterHub正确感知外部HTTPS环境:
c.JupyterHub.forwarded_port = 443 c.JupyterHub.forwarded_proto = 'https' c.JupyterHub.ip = '0.0.0.0' # 确保绑定到所有网卡,允许反向代理访问
修改后重启JupyterHub服务。
3. 检查内核启动状态
WebSocket报错可能是内核未正常启动导致的:
- 切换到
test_user账号,手动执行ipython,验证Python内核是否能正常运行 - 查看JupyterHub启动日志或默认日志文件,搜索
kernel相关条目,确认内核启动是否有报错
4. 验证Tornado版本兼容性
当前Tornado 6.4.1与JupyterHub 5.0.0理论兼容,但可尝试降级到稳定版本测试:
pip3 install tornado==6.3.3
重启JupyterHub后重新测试连接。
5. 排查网络与防火墙限制
- 检查服务器防火墙是否允许8888端口的入站流量,确保反向代理能访问JupyterHub服务
- 在服务器本地用curl测试WebSocket连接(替换xxx为实际的kernel ID):
观察是否能建立连接,排查网络层面的阻断问题curl -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Host: domain_test.com" -H "Origin: https://domain_test.com" https://domain_test.com/jhub/user/test_user/api/kernels/xxx/channels
内容的提问来源于stack exchange,提问作者Bằng Rikimaru
相关产品推荐
相关产品推荐

