昨天发了Jupyter的使用,补一篇Jupyter服务器的搭建~html
使用virtualenv建虚拟环境。在虚拟环境中安装jupyter、matplotlib等等须要的库。这里不赘述了。python
为Jupyter 相关文件准备一个目录nginx
mkdir /data/jupyter cd /data/jupyter
创建一个目录做为 Jupyter 运行的根目录ubuntu
mkdir /data/jupyter/root
咱们以须要密码验证的模式启动 Jupyter,因此要预先生成所需的密码对应的密文。
使用下面的命令建立一个密文的密码vim
python2浏览器
python -c "import IPython;print IPython.lib.passwd()"
python3 安全
python -c "import IPython;print(IPython.lib.passwd())"
执行后须要输入并确认密码,而后程序会返回一个 'sha1:...' 的密文,留好了,咱们接下来将会用到它。服务器
查看用户目录 ~/.jupyter 路径下是否存jupyter_notebook_config.py 文件。若不存在,产生此文件。测试
jupyter notebook --generate-config
编辑此文件,在最后写入url
c.NotebookApp.ip = '*' # 容许访问此服务器的 IP,星号表示任意 IP c.NotebookApp.password = u'sha1:xxx:xxx' # 以前生成的密码 hash 字串 c.NotebookApp.open_browser = False # 运行时不打开本机浏览器 c.NotebookApp.port = 8888 # 使用的端口 c.NotebookApp.enable_mathjax = True # 启用 MathJax
这时采用 IP:端口号 或者 域名:端口号的方式就能够访问正常使用了。
域名访问默认80端口,接下来咱们使用最经常使用的Nginx作代理,实现直接使用域名进行访问,隐藏端口信息。先对Jupyter进行如下修改
将配置文件ip改成只有本机才能访问
c.NotebookApp.ip = '0.0.0.0' # 127.0.0.1 也能够的
后台运行起来
nohup jupyter notebook > /dev/null 2>&1 &
$ apt-get install nginx
$ nginx -v
安装完成后,使用 nginx
命令就能够直接启动 Nginx
$ nginx
也可使用服务器
$ service nginx start $ service nginx stop $ service nginx restart
访问 http://YOUR_IP 或者 域名 就能够看到Nginx的测试页面。
配置文件在nginx目录下,nginx.conf文件中能够看到代理的部分在在这里 /etc/nginx/sites-enabled/defalut
。
$ sudo vim /etc/nginx/sites-enabled/defalut
修改其中的 location / 部分。
server { server_name DOMAIN IP_ADDRESS; # 服务器域名和 IP 地址 listen 80; ... ... location / { proxy_pass http://127.0.0.1:YOUR_PORT } }

按照上面的方法配置 Jupyter Notebook,若是仅仅对端口号进行代理转发,会出现 terminal 能够正常建立而 notebook 没法正常建立或者使用的状况。由于 Jupyter 会对 http 请求进行判断,因此反向代理时须要设置正确的信息。正确配置 nginx 反向代理的方式以下:
server { server_name DOMAIN IP_ADDRESS; # 服务器域名和 IP 地址 listen 80; ... ... location / { proxy_pass http://127.0.0.1:YOUR_PORT/; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; } }
重启Nginx服务让设置生效。
$ sudo nginx -s reload
一切正常,晚上吃鸡!不不不,开始干活!

目前的URL为 http://dyan.club/tree?
,能够在 jupyter_notebook_config.py
中增长 base_url
做为url的路径,来表示服务器上的Jupyter目录的地址。更新后的地址为 http://dyan.club/ipython/tree?
。
c.NotebookApp.base_url = '/ipython/' --制定url的path,默认是根目录
目前没有启用ssl,安全性不够,也能够增长ssl协议加强安全性。
参考文献
[1] https://bitmingw.com/2017/07/09/run-jupyter-notebook-server/
[2] https://jupyter.readthedocs.io/en/latest/install.html
[3] http://blog.takwolf.com/2016/10/19/setup-nginx-on-ubuntu/index.html
拓展阅读
[1] http://nbviewer.jupyter.org/