0%

Jupyter配合Nginx反向代理的问题

SSL Error

当 jupyter 配置了 SSL 时, Nginx 反向代理时也需要用 https 协议

例如, 反向代理到本地的 10000 端口

错误示范

1
proxy_pass http://127.0.0.1:10000;

正确示范

1
proxy_pass https://127.0.0.1:10000;

Websocket 连接问题

在基于 Docker 部署 jupyter 工作环境时, 可能会发生可以打开网页, 可以创建文件, 但是无法与后端 python 连接的情况.

查看 jupyter 日志显示

1
2
3
4
5
6
7
jupyter    | [W 2021-09-21 16:09:24.778 ServerApp] 400 GET /terminals/websocket/1 (172.27.0.1) 1.21ms referer=None
jupyter | [W 2021-09-21 16:09:26.418 ServerApp] 400 GET /terminals/websocket/1 (172.27.0.1) 1.13ms referer=None
jupyter | [W 2021-09-21 16:09:28.696 ServerApp] 400 GET /terminals/websocket/1 (172.27.0.1) 1.28ms referer=None
jupyter | [W 2021-09-21 16:09:30.660 ServerApp] 400 GET /terminals/websocket/1 (172.27.0.1) 1.24ms referer=None
jupyter | [W 2021-09-21 16:09:37.605 ServerApp] 400 GET /terminals/websocket/1 (172.27.0.1) 1.15ms referer=None
jupyter | [W 2021-09-21 16:09:41.758 ServerApp] 400 GET /terminals/websocket/1 (172.27.0.1) 1.11ms referer=None

当我尝试用 jupyter 提供的 terminal 时, 发现以上日志.

这说明这个请求没有成功, 400 状态码参考 MDN

1
HTTP 400 Bad Request 响应状态码表示由于语法无效,服务器无法理解该请求。 客户端不应该在未经修改的情况下重复此请求。

所以应该是 nginx 在与 jupyter 通信时发生了问题.

Google …

找到以下解决方案, 一个可用的 Nginx 反向代理配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

location / {
proxy_pass http://jupyter;

proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

location ~* /(api/kernels/[^/]+/(channels|iopub|shell|stdin)|terminals/websocket)/? {
proxy_pass http://jupyter;

proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

# WebSocket support
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;

}

注意添加这三项

1
2
3
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;

参考链接

https://github.com/jupyter/notebook/issues/625

https://jupyter-notebook.readthedocs.io/en/latest/config.html#options

https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Status/400

https://gist.github.com/cboettig/8643341bd3c93b62b5c2