搭建 jupyter notebook 服务(基于 systemd 和 nginx)

写在开头

在自己的服务器上搭建 jupyter notebook 服务是很方便的,可以直接在网页上修改代码、连接终端。每次重启服务器都要重新打开 notebook,很麻烦,我们可以使用 systemd 来让它开机自启。如果不想每次访问都加上端口号,那么就要使用 nginx 进行端口转发,这样我们就可以通过子域名或者子目录来访问 notebook。

笔者记录了一下整个配置的步骤,过程中还是会出现一些小坑的。配置环境为 Ubuntu 20.04,Python 3.8.5。

安装和配置 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 了。

上一篇:Spark 的 python 编程环境


下一篇:Qt编写自定义控件23-广告轮播控件