昨天發了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/