前提環境
- OS: CentOS 7.6 (x86_64)
- Python: 3.8系(Miniconda3)
- 想定利用者: 社内LANからSSHトンネル経由でアクセスするデータ分析メンバー
1. 仮想環境の作成とJupyterのインストール
# プロジェクト用仮想環境
conda create -n ml_env python=3.8 -y
conda activate ml_env
# 最小構成でインストール
conda install notebook -y
2. 設定ファイルの自動生成とパスワドハッシュの作成
# 初回起動時に設定ファイルを作成
jupyter notebook --generate-config --allow-root
# パスワドハッシュを取得(対話式)
python -c "from notebook.auth import passwd; print(passwd())"
# 出力例: sha1:abcdef123456...
得られたハッシュ文字列は後ほどjupyter_notebook_config.pyに記載します。
3. セキュアな設定を適用
~/.jupyter/jupyter_notebook_config.pyを以下のように編集します。
c = get_config()
# ネットワーク設定
c.NotebookApp.ip = '127.0.0.1' # ローカルループバックのみバインド
c.NotebookApp.port = 8889 # デフォルトを避ける
c.NotebookApp.open_browser = False # サーバ起動時にブラウザを開かない
# 認証設定
c.NotebookApp.password = u'sha1:abcdef123456...'
c.NotebookApp.token = '' # トークン無効化
c.NotebookApp.password_required = True
# セキュリティ強化
c.NotebookApp.allow_remote_access = False # 外部からの直接アクセス拒否
c.NotebookApp.allow_root = False # root権限での実行禁止
c.NotebookApp.disable_check_xsrf = False # XSRF保護を有効
4. ファイアウォールとSSHトンネルの準備
Jupyter本体は127.0.0.1:8889にバインドしているため、外部から直接アクセスできません。代わりにSSHポートフォワードを利用します。
# クライアント側(Mac/Linux/WSL)
ssh -L 8080:localhost:8889 user@your-server.com
これによりローカルのhttp://localhost:8080にアクセスすると、サーバ側のJupyterに安全に接続できますます。
5. systemdによる常駐化
nohupではなく、systemdサービスとして永続化します。
# /etc/systemd/system/jupyter-ml.service
[Unit]
Description=Jupyter Notebook for ML Environment
After=network.target
[Service]
Type=simple
User=mluser
Group=mluser
WorkingDirectory=/home/mluser/projects
Environment="PATH=/home/mluser/miniconda3/envs/ml_env/bin"
ExecStart=/home/mluser/miniconda3/envs/ml_env/bin/jupyter-notebook --config=/home/mluser/.jupyter/jupyter_notebook_config.py
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
# サービス有効化&起動
sudo systemctl daemon-reload
sudo systemctl enable jupyter-ml
sudo systemctl start jupyter-ml
sudo systemctl status jupyter-ml
6. プロセスの停止・再起動
# 停止
sudo systemctl stop jupyter-ml
# 再起動
sudo systemctl restart jupyter-ml
# ログ確認
sudo journalctl -u jupyter-ml -f
7. トラブルシューティングTips
- ポート競合時:
lsof -i:8889でプロセスを特定しkill -TERM <PID> - 設定反映:
sudo systemctl restart jupyter-mlで即時反映 - パスワド変更: 再度ハッシュを生成し
jupyter_notebook_config.pyを更新後再起動