AWS EC2 Ubuntu环境下Nginx+Gunicorn部署Jupyter Notebook求助
解决Nginx代理Jupyter Notebook到子路径且不影响原有Django站点的方案
核心问题分析
你之前的问题根源在于Jupyter默认使用根路径(/)提供服务,而Nginx将/notebook请求转发给Jupyter时,Jupyter无法识别该子路径,导致404或静态资源加载失败;同时直接在Jupyter中配置SSL会和Nginx的SSL处理冲突,引发502错误。
步骤1:修正Jupyter配置
编辑Jupyter配置文件(路径通常为~/.jupyter/jupyter_notebook_config.py,如果是新版Jupyter Server则为jupyter_server_config.py),修改以下参数:
c = get_config() # 仅监听本地,避免对外暴露8888端口,提升安全性 c.NotebookApp.ip = '127.0.0.1' c.NotebookApp.password = u'<你的密码哈希>' c.NotebookApp.port = 8888 c.NotebookApp.open_browser = False # 关键:设置Jupyter的服务根路径为/notebook c.NotebookApp.base_url = '/notebook' # 允许你的域名访问,适配HTTPS c.NotebookApp.allow_origin = 'https://www.takir.org' # 如果你使用的是Jupyter Server/nbclassic,替换为以下配置: # c.ServerApp.ip = '127.0.0.1' # c.ServerApp.password = u'<你的密码哈希>' # c.ServerApp.port = 8888 # c.ServerApp.open_browser = False # c.ServerApp.base_url = '/notebook' # c.ServerApp.allow_origin = 'https://www.takir.org'
注释掉
certfile配置,让Nginx统一处理SSL,避免证书冲突。
步骤2:调整Nginx代理配置
在你的Django站点Nginx配置文件(/etc/nginx/sites-available/<your-project>)的HTTPS server块中添加Jupyter代理规则(注意是443端口的server块,因为你的站点是HTTPS):
server { listen 443 ssl; server_name www.takir.org; # 你的SSL证书配置(保留原有内容) ssl_certificate /path/to/your/ssl/cert.pem; ssl_certificate_key /path/to/your/ssl/key.pem; # 其他原有Django站点配置(如静态文件、Gunicorn代理等,保留不变) # Jupyter代理规则 location /notebook/ { # 转发到Jupyter的base_url路径 proxy_pass http://127.0.0.1:8888/notebook/; # 传递必要的请求头,适配HTTPS和代理环境 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto $scheme; # 支持Websocket(Jupyter交互需要) proxy_http_version 1.1; proxy_redirect off; proxy_buffering off; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_read_timeout 86400; } # 原有Django站点的根路径代理(保留不变) location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } # 保留80端口重定向到HTTPS的配置(如果已有则无需修改) server { listen 80; server_name www.takir.org; return 301 https://$host$request_uri; }
步骤3:重启服务并验证
- 重启Nginx使配置生效:
sudo systemctl restart nginx - 用systemd管理Jupyter(避免终端关闭后服务停止):
创建/etc/systemd/system/jupyter.service文件:
然后启动并设置开机自启:[Unit] Description=Jupyter Notebook After=network.target [Service] User=ubuntu Environment="PATH=/home/ubuntu/anaconda3/bin:$PATH" ExecStart=/home/ubuntu/anaconda3/bin/jupyter notebook --config=/home/ubuntu/.jupyter/jupyter_notebook_config.py Restart=always [Install] WantedBy=multi-user.targetsudo systemctl daemon-reload sudo systemctl start jupyter sudo systemctl enable jupyter - 验证访问:
打开浏览器访问https://www.takir.org/notebook/,即可正常使用Jupyter,同时原有Django站点https://www.takir.org不受影响。
额外优化
- 安全组中关闭8888端口:因为Jupyter仅监听本地
127.0.0.1,无需对外暴露,减少攻击面。 - 检查文件权限:确保Nginx用户能访问代理相关路径,Jupyter配置文件权限正确。
内容的提问来源于stack exchange,提问作者LaKisha David
相关产品推荐
相关产品推荐

