Loading

搭建 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 了。

posted @   循环展开  阅读(1285)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示