Kubernetes部署Jupyter Server持续要求令牌登录,如何配置仅密码认证?
配置Jupyter Server仅密码认证(Kubernetes环境)
问题根源
默认情况下Jupyter Server每次启动会动态生成令牌,且配置未持久化,导致Pod重启或会话结束后密码/令牌失效,同时登录界面的辅助链接因环境配置问题返回404。
解决步骤
1. 生成密码哈希
在Jupyter Pod内或本地执行以下操作生成密码哈希:
- 方法1:使用内置命令
jupyter notebook password
输入目标密码后,哈希会自动写入~/.jupyter/jupyter_notebook_config.json。
- 方法2:用Python代码生成
from notebook.auth import passwd print(passwd())
复制输出的sha1:xxxxxxx:xxxxxxxxxxxx格式哈希字符串。
2. 修改Jupyter配置
生成配置文件(若未存在):
jupyter notebook --generate-config
编辑~/.jupyter/jupyter_notebook_config.py,添加/修改以下配置项:
# 禁用令牌认证,仅保留密码登录 c.NotebookApp.token = '' # 填入刚才生成的密码哈希 c.NotebookApp.password = 'sha1:xxxxxxx:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # 适配K8s集群访问,允许所有IP连接 c.NotebookApp.ip = '0.0.0.0' # 禁止自动打开浏览器(容器环境无需) c.NotebookApp.open_browser = False
3. 持久化配置到Kubernetes
由于Pod重启会丢失本地配置,需将Jupyter配置目录挂载到PVC:
- 创建PVC资源文件
jupyter-config-pvc.yaml:
apiVersion: v1 kind: PersistentVolumeClaim metadata: name: jupyter-config-pvc spec: accessModes: - ReadWriteOnce resources: requests: storage: 1Gi
执行创建命令:
kubectl apply -f jupyter-config-pvc.yaml
- 修改Jupyter Deployment的配置,添加卷挂载:
spec: containers: - name: jupyter-server image: your-jupyter-image:tag volumeMounts: # 挂载配置目录到容器内Jupyter配置路径,注意匹配容器内用户的家目录 - name: config-volume mountPath: /root/.jupyter/ # 若使用jovyan用户则为/home/jovyan/.jupyter/ volumes: - name: config-volume persistentVolumeClaim: claimName: jupyter-config-pvc
更新Deployment:
kubectl apply -f your-jupyter-deployment.yaml
4. 验证效果
重启Jupyter Pod后,访问登录界面将仅显示密码输入框,输入设置的密码即可正常登录,退出后再次登录无需重新配置,且凭证不会失效。
内容的提问来源于stack exchange,提问作者pkaramol
相关产品推荐
相关产品推荐

