后台管理工具介绍

呀嘞呀嘞,我的 JupyterLab 怎么又挂了。

简单的 nohup [CMD] & 已经不够用,该研究一下后台管理工具了。

问了一下 Qwen,大概有五款后台管理工具可用。这五款工具大致可分为两类:

  • 进程管理器:systemd, pm2, supervisor
  • 终端复用器:screen, tmux

总之,保持单个程序在后台运行,systemd 就够用。如果要维持多个后台程序,pm2 比较合适。screentmux 则是更临时的方案,适合偶尔用用的情况。

一、systemd

使用 systemd 管理 Jupyter lab 服务,必须先创建一个 systemd unit 文件来定义服务的启动、重启等行为。以下是创建 systemd 服务的步骤。

1.1 创建 unit 文件

vi 新建并打开 jupyterlab.service 文件:

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

配置如下:

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

[Service]
Type=simple
User=[YOUR_USERNAME]
ExecStart=/home/[YOUR_USERNAME]/miniconda3/bin/jupyter lab --ip=0.0.0.0 --port=443 --no-browser --allow-root
WorkingDirectory=/home/[YOUR_USERNAME]/
Restart=on-failure
RestartSec=8s

[Install]
WantedBy=multi-user.target
  • [YOUR_USERNAME] 替换为你的用户名。如果你在 root 上开服务,记得在 ExecStart 后加一个 --allow-root
  • 如果你的服务不在 https 上,请用 --port=80--port=8888 之类的其他端口
  • 在 https 上搭建 jupyter lab 服务的方法,参见 在服务器上使用 JupyterLab

1.2 启动服务

1)重启守护进程,使新增的 systemd unit 文件生效。

sudo systemctl daemon-reload

2)启动 jupyter lab 服务

sudo systemctl start jupyterlab

注意,这里的服务名应和 jupyterlab.service 文件名相同

3)开机自启

sudo systemctl enable jupyterlab

4)检查服务状态

sudo systemctl status jupyterlab

ps -ef | grep jupyter

5)停止或重启服务

sudo systemctl stop jupyterlab
sudo systemctl restart jupyterlab

平替:supervisor 是一款 systemd 的平替,操作都蛮像的。

二、pm2

pm2 是一个自带负载均衡的生产环境进程管理器。

2.1 安装

对于 Centos,安装 Node.jsnpm

sudo yum install epel-release
sudo yum install nodejs npm

全局安装 pm2

sudo npm install -g pm2

2.2 Shell 启动脚本

写一个名为 jp.sh 的启动脚本:

#!/bin/bash

# 如果不是全局 conda 环境
/path/to/your/miniconda3/bin/activate [YOUR_ENV]

jupyter-lab --ip=0.0.0.0 --port=443 --no-browser --notebook-dir=/home  --allow-root

给脚本执行权限:

chmod +x ./jp.sh

2.3 启动 pm2

使用 pm2 启动这个脚本:

pm2 start ./jp.sh

# 带重启策略的启动
pm2 start ./jp.sh --restart-on-failure

查看 pm2 的状态:

# 查看状态
pm2 status

# 查看日志
pm2 logs jp

进程保持:

# 保存当前 list 以保证它在开机时自启
pm2 save

# 保证 pm2 开机自启
pm2 startup

停止和删除进程:

# 停止 jp 进程
pm2 stop jp

# 停止所有进程
pm2 stop all

# 删除所有进程
pm2 delete all

# 重置 pm2 环境(可选)
pm2 reset all

# 查看删除是否生效
pm2 list

三、screen

Screen 是一个终端复用工具,用它也可以实现后台运行 jupyter 服务。下面以 jupyter notebook 为例。

3.1 安装 Screen

在 Ubuntu 上安装:

sudo apt-get install screen

在 Centos 安装:

# 更新系统中的所有包
sudo yum update

# 启用 EPEL 仓库 (Extra Packages for Enterprise Linux)
sudo yum install epel-release

# 安装 screen
sudo yum install screen

# 测试 screen 是否安装成功
screen --version

3.2 开启会话

开启一个名为 jp 的会话:

screen -S jp

在新会话里启动 jupyter notebook:

jupyter notebook --ip=0.0.0.0 --port=443 --allow-root

3.3 离开会话

ctrl + a 然后按 d 暂时离开会话。

3.4 重回会话

列出所有 screen 会话:

screen -ls

重回 jp 会话:

screen -r jp

退出会话:

exit

平替:tmux 也很常用,两款工具都支持分屏。没有深究它俩有什么区别,看上去就是界面风格的区别。

参考: