May 16, 2025

[Python] #1 Jupyter Kernel Server

[Python] #1  Jupyter Kernel Server
VScode use Jupyter Kernel in container

Python on container

작업환경도 code-server로 k8s에 올렸는데, 런타임도 올리고 싶었습니다.
python을 container로 올리고 런타임을 연결해서 작업하려면 ssh로 container에 들어가서 작업을 해야 한다고 하더라구요.

그래서 그냥 Jupyter를 구성하기로 했습니다. 개발도 Jupyter Notebook으로 하긴 하니까 그게 맘 편하겠다 생각했습니다.

Jupyter on k8s

JupyterHub를 이용하는 방법이 가장 많이 알려진 방법입니다. 다중 사용자 처리하기도 쉽고 git 연동이나 다른 서비스도 많아서 좋긴 한데, 리소스도 많이 쓰고 ide를 code-server로 한 순간부터 조금 불필요하다고 생각해서 python에 jupyter kernel만 이용하기로 했습니다.

python:3.11-slim 이미지에 jupyter와 원하는 패키지를 설치합니다.
저는 머신러닝 좀 하려고 pytorch와 pandas를 같이 설치했습니다.

  1. --MappingKernelManager.cull_idle_timeout
    1. 커널 미사용 시 끊기는 시간
  2. --NotebookApp.token=''
    1. 커널에 연결하려면 token과 같이 사용해서 연결해야 합니다.
      저는 내부에서만 사용할 거라 토큰은 없이 하겠습니다.
apiVersion: v1
kind: Pod
metadata:
  name: python-kernel
  namespace: python
  labels:
    app: python-kernel
spec:
  # nodeSelector:
  #   gpu: nvidia
  containers:
    - name: python
      image: python:3.11-slim
      ports:
        - containerPort: 8888
      command: 
        - "sh"
        - "-c"
        - |
          pip install pandas jupyter
          pip3 install torch --index-url https://download.pytorch.org/whl/cpu
          jupyter notebook --ip=0.0.0.0 --port=8888 --no-browser --allow-root --MappingKernelManager.cull_idle_timeout=600 --NotebookApp.token=''
---
apiVersion: v1
kind: Service
metadata:
  name: python-kernel
  namespace: python
spec:
  type: ClusterIP
  ports:
    - port: 8888
      targetPort: 8888
  selector:
    app: python-kernel

kubectl logs -n python python-kernel 로 로그를 보시고 다음과 같은 내용이 나오면 됩니다.
token을 사용하시는 분은 url을 전부 복사하셔서 사용하시면 됩니다.

Jupyter Running

이제 https://python-kernel.python.svc.cluster.local:8888 에 kernel이 작동 중입니다. 이제 연결을 해봅시다.

VSCode Jupyter Kernel 연결

  1. .ipynb 확장자로 jupyter notebook을 만들고 kernel을 클릭해 줍니다.
  1. Existing Jupyter Server... -> Enter the URL of running Jupyter Server
  2. "https://python-kernel.python.svc.cluster.local:8888" 를 입력합니다.
  1. 토큰이 없는 것을 확인하고 (토큰은 /?token=(token) 으로 입력하시면 됩니다. )
  2. 이제 Kernel이 연결된 Jupyter를 사용하시면 됩니다.
  3. 참고로 실행되는 위치는 kernel이 설치된 Pod 이기 때문에, 파일을 사용하시려면 kernel Pod에 연결하셔야 합니다.

Jupyter Kernel을 default로 연결하는 방법

k8s로 구성하다 보니까 껏다 켜져도 자동으로 연결이 되게 하고 싶은데, settings에 jupyterServerType, remoteUrl, defaultKernel을 설정해줘도 안되더라구요.

그래도 한번 연결하고 Pod가 꺼지지 않으면 설정이 남아 있고, 비밀번호도 없으니까 쓰긴 하는데, 아시는 분이 있으시면 알려주시기 바랍니다.

Comments