1. 程式人生 > 實用技巧 >搭建 jupyter notebook 服務(基於 systemd 和 nginx)

搭建 jupyter notebook 服務(基於 systemd 和 nginx)

寫在開頭

在自己的伺服器上搭建 jupyter notebook 服務是很方便的,可以直接在網頁上修改程式碼、連線終端。每次重啟伺服器都要重新開啟 notebook,很麻煩,我們可以使用 systemd 來讓它開機自啟。如果不想每次訪問都加上埠號,那麼就要使用 nginx 進行埠轉發,這樣我們就可以通過子域名或者子目錄來訪問 notebook。

筆者記錄了一下整個配置的步驟,過程中還是會出現一些小坑的。配置環境為 Ubuntu 20.04,Python 3.8.5。

轉載請標明出處 https://www.cnblogs.com/xkgeng/p/14010306.html

安裝和配置 Jupyter

安裝 pip3

sudo apt install python3-pip

安裝 jupyter,國內的伺服器可以先新增映象源,加快速度

sudo pip3 install jupyter --user

設定密碼

jupyter notebook password

之後就可以手動開啟 jupyter 了

jupyter notebook --no-browser --ip 0.0.0.0

使用 Systemd 管理 Jupyter

向 /etc/systemd/system/jupyter.service 中新增如下內容,注意將使用者名稱 admin 改成自己的;如果剛才 pip3 安裝時沒有加 --user,那就還要更改 jupyter 的啟動路徑

[Unit]
Description=Jupyter
After=syslog.target network.target

[Service]
User=admin
Environment="PATH=/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/home/admin/.local/bin"
WorkingDirectory=/home/admin/lab/
ExecStart=/home/admin/.local/bin/jupyter notebook --ip=0.0.0.0 --no-browser

Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target

重新載入服務

sudo systemctl daemon-reload

啟動服務

sudo systemctl start jupyter

檢視狀態

sudo systemctl status jupyter

設為開機自啟

sudo systemctl enable jupyter

安裝和配置 Nginx

安裝 nginx

sudo apt install nginx

下一步就是配置 nginx 檔案,我這裡是通過子域名(lab)來訪問 notebook,埠號使用預設的。因為 jupyter notebook 中有連線終端的功能,所以要使用下面的 nginx 配置檔案,否則遠端終端會用不了。

向 /etc/nginx/sites-available/lab 中寫入,注意將 example.com 更換為你自己的域名

server {
        listen 80;

        server_name lab.example.com;

        location / {
                proxy_pass http://localhost:8888;
                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;
        }
}

儲存退出後建立軟連線

sudo ln -s /etc/nginx/sites-available/lab /etc/nginx/sites-enabled/lab

重新載入 nginx 配置

sudo nginx -s reload

這樣我們就能通過訪問 lab.example.com 來進入自己的 notebook 了。