背景

最近学习发现电脑换来换去很麻烦, 然后就想到要把 Jupyter 部署在云服务器上, 正好服务器放在腾讯云也吃灰很久了, 就拿来玩一玩. 这里的所有操作都基于 Centos , 当然 Ubuntu 也适用, 但是要将教程中所有 root 换成 home/用户名 , 比如 home/ubuntu .

部署 Jupyter

安装 Anaconda

可以前往清华镜像源选择对应版本, 找到你想要的 Anaconda3 版本, 通过下面的指令进行下载

1
wget https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/Anaconda3-2020.07-Linux-x86_64.sh  # Anaconda3-2020.07-Linux-x86_64.sh 可以更换成你自己选择的版本

然后安装

1
bash Anaconda3-2020.07-Linux-x86_64.sh  # 同样更换你自己选择的版本

然后一路 enter / yes 就完事.

添加环境变量

接着添加环境变量.

1
sudo vi /etc/profile

输入密码后进入文件进行编辑. 在最底下加入两行

1
2
# Anaconda
export PATH="/root/anaconda3/bin:$PATH"

如果搞不懂服务器中文件的编辑 (vim) 的话, 可以百度一下, 很多教程的. 编辑完后, 按 ESC 后输入 :wq 然后 enter 保存文件并退出 vi.

然后

1
source ~/.bashrc

接着重启服务器

1
reboot

重启完成后验证是否安装成功

1
conda

成功就不会报错.

配置 Jupyter

进入 Python

1
python

然后

1
2
from notebook.auth import passwd
passwd()

接着它就会让你输入密码, 输入你想要设置的密码并再确认一次, 然后它就会生成一串密匙

1
'sha1:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

复制下来, 然后生成配置文件

1
jupyter lab --generate-config

进入配置文件并修改

1
vi /root/.jupyter/jupyter_notebook_config.py

然后修改一下配置项, 如果要修改就将其前面的注释符号 # 删除

1
2
3
4
5
6
c.NotebookApp.ip = '*'
c.NotebookApp.password = u'sha1:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # 就是那串你复制的密匙
# 这个部分可改可不改, 不改就不要删除注释符号
c.NotebookApp.notebook_dir = '/tree' # 输入要 jupyter 开启的目录, 如果不修改, 那么就会默认在输入命令的目录下打开
c.NotebookApp.open_browser = False # 禁止自动打开浏览器
c.NotebookApp.allow_root = True # 允许 root 启动

然后就可以了

启动

1
jupyter lab

然后打开浏览器进入

1
云服务器ip:8888

然后输入你刚刚设置的密码就可以进入了.

PM2 进程托管

但是此时你必须一直开着服务器的终端不然 Jupyter 就会退出, 很不方便, 因此我们使用 PM2 来托管进程.

安装 Node.js

使用下列命令安装

1
2
3
wget -qO- https://raw.github.com/creationix/nvm/master/install.sh | sh
source ~/.bash_profile # 如果是 Ubuntu 改成 source ~/.bashrc
nvm install stable

安装并使用 PM2

1
npm install pm2 -g

如果下载太慢先换成淘宝源

1
npm config set registry https://registry.npm.taobao.org

然后再试一次

1
npm install pm2 -g

在任意的目录新建文件 jupyter.js , 然后写入如下内容

1
2
3
4
5
6
7
8
9
10
//run
const { exec } = require('child_process')
exec('jupyter lab',(error, stdout, stderr) => {
if(error){
console.log('exec error: ${error}')
return
}
console.log('stdout: ${stdout}');
console.log('stderr: ${stderr}');
})

然后保存退出, 执行脚本

1
pm2 start jupyter.js

就可以愉快的在服务器上使用 Jupyter 啦!