在 Ubuntu 24.04 Server 上部署 Jupyter

在 Ubuntu 24.04 上部署 Jupyter

使用 pip 安装(推荐用于个人使用)

名称的由来

这个名字非常有意义,它源于其支持的三种核心编程语言的首字母缩写:

  • Ju - Julia

  • P - Python

  • R - R

尽管名字来源于这三种语言,但 Jupyter 现在已经通过“内核”支持超过 40 种 编程语言,包括 Scala、Java、JavaScript 等。

核心概念与组成部分

要更好地理解 Jupyter,我们需要了解它的几个核心部分:

  1. Jupyter Notebook

    • 这是 Jupyter 最广为人知的产品。它是一个 .ipynb 格式的文档,你可以在一个文档里交替编写:

      • 代码:可以直接运行并看到结果。

      • Markdown 文本:用于写注释、说明、标题。

      • 公式:支持 LaTeX 编写数学公式。

      • 丰富的输出:如图表、视频、图像、HTML 等。

    • 特点:非常适合做探索性数据分析教学演示原型开发,因为代码可以分块运行,方便调试和迭代。

  2. JupyterLab

    • 这是 Jupyter 的“下一代”用户界面。你可以把它看作一个集成开发环境

    • 在 JupyterLab 中,你不仅可以打开 Notebook,还可以同时打开文本编辑器、终端、数据文件查看器、交互式控件等多个面板,布局更灵活,功能更强大。

    • 可以理解为:JupyterLab 是一个工作台,而 Notebook 是这个工作台上的一个重要工具。

  3. Jupyter Kernel(内核)

    • “内核”是负责执行代码的“引擎”。当你运行代码时,实际上是内核在执行计算并返回结果。

    • Jupyter 的界面(Notebook 或 Lab)和内核是分离的。这意味着你可以在本地界面上操作,但连接到一个运行在远程服务器甚至超级计算机上的强大内核。

1. 安装 Python 和 pip

sudo apt update
sudo apt install python3 python3-pip python3-venv

2. 创建虚拟环境(推荐)

# 创建项目目录
mkdir jupyter_project
cd jupyter_project

# 创建虚拟环境
python3 -m venv jupyter_env

# 激活虚拟环境
source jupyter_env/bin/activate

3. 安装 Jupyter

pip install jupyterlab
# 或者安装经典的 Jupyter Notebook
# pip install notebook

4. 生成配置文件

jupyter lab --generate-config
# 或者对于 notebook
# jupyter notebook --generate-config

5. 设置密码

jupyter lab password
# 输入并确认你的密码

6. 修改配置文件

编辑 ~/.jupyter/jupyter_lab_config.py


# Configuration file for lab.

c = get_config()  #noqa

c.ServerApp.ip = '0.0.0.0'  # 允许外部访问
c.ServerApp.port = 3333     # 端口号
c.ServerApp.open_browser = False  # 不自动打开浏览器
c.ServerApp.password = 'argon2:$argonHBD+q4' # 上面设置的密码hash
c.ServerApp.root_dir = '/root/notebooks'  # 笔记本目录
c.ServerApp.allow_root = True

7. 启动 Jupyter

jupyter lab
# 或
jupyter notebook

8.配置supervisor 自动启动

新建jupyter.conf

image

内容如下

root@VM-4-9-ubuntu:/etc/supervisor/conf.d# cat jupyter.conf
[program:Jupyter.Server]
directory = /root/jupyter_project/
command = /bin/bash -c "cd /root/jupyter_project&&source jupyter_env/bin/activate&&jupyter lab"
user = root
stopsignal=INT
autostart=true
autorestart=true
stopasgroup = true
killasgroup = true
redirect_stderr = true
startsecs=1
stdout_logfile = /var/log/odoo/jupyter.log
stderr_logfile = /var/log/odoo/jupyter.error.log

重启supervisor

root@VM-4-9-ubuntu:/etc/supervisor/conf.d# service supervisor restart

访问 Jupyter

在浏览器中访问:

http://your_server_ip:3333

常用命令

  • 查看运行状态:jupyter lab list
(jupyter_env) root@VM-4-9-ubuntu:~/jupyter_project# jupyter lab list
Currently running servers:
http://VM-4-9-ubuntu:3333/ :: /root/notebooks
(jupyter_env) root@VM-4-9-ubuntu:~/jupyter_project#

  • 停止服务:jupyter lab stop 8888
  • 安装内核:pip install ipykernel
  • 添加内核:python -m ipykernel install --user --name=myenv