使用Docker搭建jupyterhub,并采用sqlite3数据库验证登录

先pip安装好DockerSpawner

pip install dockerspawner

拉取相关镜像

docker pull jupyterhub/jupyterhub
docker pull jupyterhub/singleuser

 创建jupy_network网络

docker network create --driver bridge jupyterhub_network

创建jupyterhub的volume,也就是把jupyterhub_config和sqlite数据库文件都放在/data/jupyterhub里

sudo mkdir -pv /data/jupyterhub
sudo chown -R root /data/jupyterhub
sudo chmod -R 777 /data/jupyterhub

jupyterhub_config配置文件如下

c = get_config()
from jupyterhub.auth import Authenticator
from tornado import gen

import os
import sqlite3

# 重写验证类,使用sqlite数据库验证
class SQLiteAuthenticator(Authenticator):

    """JupyterHub Authenticator Based on SQLite"""

    def __init__(self, **kwargs):
        super(SQLiteAuthenticator, self).__init__(**kwargs)

    @staticmethod
    def _verify_password(username, password):
        try:
            # to define sqlite db location in hub images
            os.environ["JUPYTERHUB_SQLITEDB_PATH"]="/srv/jupyterhub/user.db"

            sql_cnn = sqlite3.connect(os.getenv('JUPYTERHUB_SQLITEDB_PATH'))
            cursor = sql_cnn.cursor()
            sql = ("SELECT `password` FROM users WHERE `username` = '{}'").format(username)
            cursor.execute(sql)

            user_passwd = cursor.fetchone()[0]
            input_passwd = password

            if user_passwd == input_passwd:
                cursor.close()
                sql_cnn.close()
                return True
            else:
                cursor.close()
                sql_cnn.close()
                return False
        except:
            cursor.close()
            sql_cnn.close()
            return False

    @gen.coroutine
    def authenticate(self, handler, data):
        username = data['username']
        passwd = data['password']

        if self._verify_password(username, passwd):
            return data['username']
        else:
            return None

c.JupyterHub.ip = '0.0.0.0'
c.JupyterHub.port = 80
c.Authenticator.admin_users = {'jiangyu'}


c.JupyterHub.authenticator_class = SQLiteAuthenticator
c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner'
c.DockerSpawner.image = 'dhso/jupyter_lab_singleuser:latest'

# 使用jupyterlab
c.DockerSpawner.extra_create_kwargs.update({ 'command': "start-singleuser.sh --SingleUserNotebookApp.default_url=/lab" })
network_name = 'jupyterhub_network'
c.DockerSpawner.use_internal_ip = True
c.DockerSpawner.network_name = network_name
c.DockerSpawner.extra_host_config = { 'network_mode': network_name }
notebook_dir = '/home/jovyan/work'
c.DockerSpawner.volumes = { 'jupyterhub-user-{username}': notebook_dir }
c.DockerSpawner.remove_containers = True
c.DockerSpawner.debug = True
#c.JupyterHub.hub_ip = 'jupyterhub'

######c.JupyterHub.hub_ip需要配置
#from jupyter_client.localinterfaces import public_ips
#c.JupyterHub.hub_ip = public_ips()[0]
c.JupyterHub.hub_ip = '0.0.0.0' 
#c.JupyterHub.hub_port = 8081

使用Dockerfile构造jupyterhub镜像

docker build -t my/jupyterhub .

Dockerfile内容如下:

ARG BASE_IMAGE=jupyterhub/jupyterhub
FROM ${BASE_IMAGE}

# 改变apt源,加快构建速度
RUN sed -i s@/archive.ubuntu.com/@/mirrors.aliyun.com/@g /etc/apt/sources.list
RUN apt-get clean
RUN apt-get update
RUN apt-get install sqlite3
RUN apt-get install vim -y

RUN pip install --no-cache --upgrade jupyter -i http://pypi.douban.com/simple/ --trusted-host=pypi.douban.com/simple
RUN pip install --no-cache dockerspawner -i http://pypi.douban.com/simple/ --trusted-host=pypi.douban.com/simple
RUN pip install --no-cache oauthenticator -i http://pypi.douban.com/simple/ --trusted-host=pypi.douban.com/simple

EXPOSE 5678

再构造单用户jupyter的镜像,

docker build -t dhso/jupyter_lab_singleuser .

Dockerfile内容如下:

ARG BASE_IMAGE=jupyterhub/singleuser
FROM ${BASE_IMAGE}
# 加速
# RUN conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
# RUN conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
# RUN conda config --set show_channel_urls yes
# Install jupyterlab
# RUN conda install -c conda-forge jupyterlab

# 如果要预装一些库的话,则在这里就要写好命令
# 预装pandas、numpy、matplotlib
RUN pip install pandas numpy matplotlib -i http://pypi.douban.com/simple/ --trusted-host=pypi.douban.com/simple

RUN pip install jupyterlab
RUN jupyter serverextension enable --py jupyterlab --sys-prefix
USER jovyan

最后创建容器

docker run -d --name jupyterhub -p 0.0.0.0:5678:80 \
--network jupyterhub_network \
-v /var/run/docker.sock:/var/run/docker.sock \
-v /data/jupyterhub:/srv/jupyterhub my/jupyterhub:latest

# -v表示把本地的目录挂在到容器目录中
# 第一个-v是将前面的singleuser镜像挂载到容器里
# 第二个-v是将配置文件和数据库文件挂载到容器里

最后访问localhost:5678即可访问jupyterhub

你可能感兴趣的:(docker,sqlite3)