笔者使用jupyter的场景是: LAN中的一台Linux主机,跑jupyter,在LAN中通过自己的笔记本用浏览器访问jupyter,笔记本上写代码,主机跑代码。
遇到的问题是:笔记本上通过SSH登录主机,jupyter notebook
启动jupyter后,却无法通过本地浏览器访问主机jupyter。
调试过程
1 本地可以通过SSH/ping访问主机,网络无问题
2 关闭主机的防火墙,无效
3 jupyter版本检查,确保不是老版本(可能存在bug)
4 查看jupyter命令,参考官方文档http://jupyter.readthedocs.io/en/latest/projects/jupyter-command.html,确保命令没用错
5 jupyter配置检查,参考官方文档http://jupyter.readthedocs.io/en/latest/projects/config.html
(1) 生成一份默认配置文件
(adog) [root@dog0 bin_yin]# jupyter notebook --generate-config
Writing default config to: /root/.jupyter/jupyter_notebook_config.py
(2) 查看配置文件
(adog) [root@dog0 bin_yin]# vim /root/.jupyter/jupyter_notebook_config.py
(3) 发现可疑配置
# The IP address the notebook server will listen on.
# c.NotebookApp.ip = 'localhost'
将其改为监听所有IP,并去掉注释使之生效
# The IP address the notebook server will listen on.
c.NotebookApp.ip = '*'
(4) 再启动jupyter(jupyter notebook
),就能通过浏览器访问jupyter了
更简单的解决方法
启动jupyter时就通过参数指定jupyter监听LAN内的所有IP。
jupyter notebook --ip="*"
奇怪的是这种配置方式jupyter官方的jupyter命令文档并未给出,jupyter -h
的说明里也没有--ip
这个参数。
经过与jupyter开发团队的交流,得知这些选项都不会单独说明,但可以参考这个文档来利用类似的参数。
记住这个jupyter启动命令
我们一般用SSH连接到主机,启动jupyter后,就会退出SSH登录(SSH session超时也会关闭)。SSH session关闭时,会向该SSH控制终端创建的所有进程发送SIGHUP信号(signal hang up),即终止进程。
所以我们退出SSH,或SSH自己超时关闭后,就不能通过浏览器访问jupyter了。怎么办呢,Linux有一个命令nohup
,用于声明这个进程不响应SIGHUP信号。所以下面这个jupyter命令,即解决了LAN内跨主机访问的问题,也解决了SSH退出导致jupyter进程终止的问题。
nohup jupyter notebook --ip="*"
下面是更完善的用法,在linux下,长期使用jupyter,就用这个命令
nohup jupyter notebook --allow-root --no-browser --ip="*" &