Jupyter lab

在 ubuntu 上配置 jupyter 并在后台运行和自动启动

在 Ubuntu 22.04 上安装 JupyterLab 并配置为 systemd 服务

环境说明

  • 系统:Ubuntu 22.04

  • 虚拟环境名称:lihaoyang

  • JupyterLab 端口:2024

  • 访问密码:lihaoyang123

1. 创建并激活 Conda 虚拟环境

首先,使用 Miniconda 创建并激活一个名为 lihaoyang 的虚拟环境:

# 创建虚拟环境 lihaoyang
conda create -n lihaoyang python=3.10

# 激活虚拟环境
conda activate lihaoyang

2. 安装 JupyterLab

在激活的 lihaoyang 环境中,安装 JupyterLab:

# 安装 JupyterLab
conda install -c conda-forge jupyterlab

3. 生成并配置 JupyterLab 配置文件

生成 JupyterLab 的配置文件:

# 生成配置文件
jupyter lab --generate-config

配置文件默认生成在 /root/.jupyter/jupyter_lab_config.py。将其移动到虚拟环境目录:

# 创建配置目录
mkdir -p /root/miniconda3/envs/lihaoyang/etc/jupyter

# 移动配置文件
mv /root/.jupyter/jupyter_lab_config.py /root/miniconda3/envs/lihaoyang/etc/jupyter/

4. 设置 JupyterLab 访问密码

在虚拟环境中生成密码哈希:

# 进入 Python 交互模式
python

# 在 Python 交互模式中输入以下代码生成密码哈希:
from jupyter_server.auth import passwd
passwd()  # 输入 lihaoyang123

复制生成的哈希(形如 sha1:yourhashedpassword),并编辑配置文件 /root/miniconda3/envs/lihaoyang/etc/jupyter/jupyter_lab_config.py

nano /root/miniconda3/envs/lihaoyang/etc/jupyter/jupyter_lab_config.py

添加或修改以下内容:

c.ServerApp.port = 2024                 # 端口
c.ServerApp.ip = '0.0.0.0'              # 允许外部访问
c.ServerApp.open_browser = False        # 禁用自动打开浏览器
c.ServerApp.password = 'sha1:yourhashedpassword'  # 使用生成的哈希

5. 配置 JupyterLab 为 systemd 服务

创建 systemd 服务文件:

sudo nano /etc/systemd/system/jupyterlab.service

在文件中添加以下内容:

[Unit]
Description=JupyterLab Service

[Service]
Type=simple
ExecStart=/root/miniconda3/envs/lihaoyang/bin/jupyter lab --allow-root
WorkingDirectory=/root/lihaoyang
Environment="PATH=/root/miniconda3/envs/lihaoyang/bin"
Environment="PATH=/usr/bin:/bin:/root/miniconda3/envs/lihaoyang/bin:/root/miniconda3/bin:/condabin"
Environment="SHELL=/usr/bin/bash"
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

6. 启用并启动 JupyterLab 服务

加载 systemd 配置并启动服务:

sudo systemctl daemon-reload
sudo systemctl enable jupyterlab
sudo systemctl start jupyterlab

检查服务状态以确保成功运行:

sudo systemctl status jupyterlab

7. 访问 JupyterLab

在浏览器中访问 http://<your-server-ip>:2024,使用设置的密码 lihaoyang123 登录。

8. 常用管理命令

  • 查看服务状态:

    sudo systemctl status jupyterlab
  • 重启服务:

    sudo systemctl restart jupyterlab
  • 停止服务:

    
    sudo systemctl stop jupyterlab
  • 查看服务日志:

    
    journalctl -xe -u jupyterlab

以上步骤完成后,JupyterLab 将在端口 2024 上运行并自动重启,配置了基础访问密码 lihaoyang123。确保服务器的防火墙规则允许端口 2024 的访问。

Last updated