

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 자체 호스팅 Jupyter Notebook 사용
<a name="managed-endpoints-self-hosted"></a>

Jupyter 또는 JupyterLab 노트북을 Amazon EC2 인스턴스 또는 자체 Amazon EKS 클러스터에서 *자체 호스팅 Jupyter Notebook*으로 호스팅하고 관리할 수 있습니다. 그런 다음 자체 호스팅 Jupyter Notebook으로 대화형 워크로드를 실행할 수 있습니다. 다음 섹션에서는 Amazon EKS 클러스터에 자체 호스팅 Jupyter Notebook을 설정하고 배포하는 프로세스를 안내합니다.



**Topics**
+ [

## 보안 그룹 생성
](#managed-endpoints-self-hosted-security)
+ [

## Amazon EMR on EKS 대화형 엔드포인트 생성
](#managed-endpoints-self-hosted-create-me)
+ [

## 대화형 엔드포인트의 게이트웨이 서버 URL 검색
](#managed-endpoints-self-hosted-gateway)
+ [

## 인증 토큰을 검색하여 대화형 엔드포인트에 연결
](#managed-endpoints-self-hosted-auth)
+ [

## 예제: JupyterLab 노트북 배포
](#managed-endpoints-self-hosted-example)
+ [

## 자체 호스팅 Jupyter Notebook 삭제
](#managed-endpoints-self-hosted-cleanup)

## 보안 그룹 생성
<a name="managed-endpoints-self-hosted-security"></a>

대화형 엔드포인트를 생성하고 자체 호스팅 Jupyter 또는 JupyterLab 노트북을 실행하려면 먼저 노트북과 대화형 엔드포인트 간 트래픽을 제어하는 보안 그룹을 생성해야 합니다. Amazon EC2 콘솔 또는 Amazon EC2 SDK를 사용하여 보안 그룹을 생성하려면 **Amazon EC2 사용 설명서에서 [보안 그룹 생성](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/working-with-security-groups.html#creating-security-group)의 단계를 참조하세요. 노트북 서버를 배포하려는 VPC에서 보안 그룹을 생성해야 합니다.

이 안내서의 예제를 따르려면 Amazon EKS 클러스터와 동일한 VPC를 사용합니다. Amazon EKS 클러스터의 VPC와 다른 VPC에서 노트북을 호스팅하려면 두 VPC 사이에서 피어링 연결을 생성해야 할 수 있습니다. 두 VPC 사이에서 피어링 연결을 생성하는 단계는 Amazon VPC 시작 안내서의 [VPC 피어링 연결 생성](https://docs.aws.amazon.com/vpc/latest/peering/create-vpc-peering-connection.html)을 참조하세요.

다음 단계에서 [Amazon EMR on EKS 대화형 엔드포인트를 생성](https://docs.aws.amazon.com/)하려면 보안 그룹의 ID가 필요합니다.

## Amazon EMR on EKS 대화형 엔드포인트 생성
<a name="managed-endpoints-self-hosted-create-me"></a>

노트북용 보안 그룹을 생성한 후에는 [가상 클러스터의 대화형 엔드포인트 생성](create-managed-endpoint.md)에 제공된 단계를 사용하여 대화형 엔드포인트를 생성합니다. [보안 그룹 생성](#managed-endpoints-self-hosted-security)에서 노트북용으로 생성한 보안 그룹 ID를 제공해야 합니다.

다음 구성 재정의 설정에서 *your-notebook-security-group-id* 위치에 보안 ID를 삽입합니다.

```
--configuration-overrides '{
    "applicationConfiguration": [
        {
            "classification": "endpoint-configuration",
            "properties": {
                "notebook-security-group-id": "your-notebook-security-group-id"
            }
        }
    ],
    "monitoringConfiguration": {
    ...'
```

## 대화형 엔드포인트의 게이트웨이 서버 URL 검색
<a name="managed-endpoints-self-hosted-gateway"></a>

대화형 엔드포인트를 생성한 후 AWS CLI에서 `describe-managed-endpoint` 명령을 사용하여 게이트웨이 서버 URL을 검색합니다. 노트북을 엔드포인트에 연결하려면 이 URL이 필요합니다. 게이트웨이 서버 URL은 프라이빗 엔드포인트입니다.

```
aws emr-containers describe-managed-endpoint \
--region region \
--virtual-cluster-id virtualClusterId \
--id endpointId
```

처음에 엔드포인트 상태는 **CREATING**입니다. 몇 분 후 **ACTIVE** 상태로 전환됩니다. 엔드포인트 상태가 **ACTIVE**인 경우 사용할 준비가 된 것입니다.

`aws emr-containers describe-managed-endpoint` 명령이 활성 엔드포인트에서 반환하는 `serverUrl` 속성을 기록합니다. [자체 호스팅 Jupyter 또는 JupyterLab 노트북을 배포](https://docs.aws.amazon.com/)할 때 노트북을 엔드포인트에 연결하려면 이 URL이 필요합니다.

## 인증 토큰을 검색하여 대화형 엔드포인트에 연결
<a name="managed-endpoints-self-hosted-auth"></a>

Jupyter 또는 JupyterLab 노트북에서 대화형 엔드포인트에 연결하려면 `GetManagedEndpointSessionCredentials` API를 사용하여 세션 토큰을 생성해야 합니다. 토큰은 대화형 엔드포인트 서버에 연결하기 위한 인증 증명 역할을 합니다.

다음 명령은 아래 출력 예제를 통해 더 자세히 설명됩니다.

```
aws emr-containers get-managed-endpoint-session-credentials \
--endpoint-identifier endpointArn \
--virtual-cluster-identifier virtualClusterArn \
--execution-role-arn executionRoleArn \
--credential-type "TOKEN" \
--duration-in-seconds durationInSeconds \
--region region
```

**`endpointArn`**  
엔드포인트의 ARN. `describe-managed-endpoint` 직접 호출 결과에서 ARN을 찾을 수 있습니다.

**`virtualClusterArn`**  
가상 클러스터의 ARN.

**`executionRoleArn`**  
실행 역할의 ARN.

**`durationInSeconds`**  
토큰이 유효한 기간(초). 기본 기간은 15분(`900`)이고 최대 기간은 12시간(`43200`)입니다.

**`region` **  
엔드포인트와 동일한 리전.

출력은 다음 예제와 비슷합니다. [자체 호스팅 Jupyter 또는 JupyterLab 노트북을 배포](https://docs.aws.amazon.com/)할 때 사용할 `session-token` 값을 기록합니다.

```
{
    "id": "credentialsId",
    "credentials": {
        "token": "session-token"
    },
    "expiresAt": "2022-07-05T17:49:38Z"
}
```

## 예제: JupyterLab 노트북 배포
<a name="managed-endpoints-self-hosted-example"></a>

위 단계를 완료했으면 이 예제 절차를 시도하여 대화형 엔드포인트가 있는 Amazon EKS 클러스터에 JupyterLab 노트북을 배포할 수 있습니다.

1. 네임스페이스를 생성하여 노트북 서버를 실행합니다.

1. 다음 콘텐츠를 포함하는 `notebook.yaml` 파일을 로컬로 생성합니다. 아래에서 파일 콘텐츠를 설명합니다.

   ```
   apiVersion: v1
   kind: Pod
   metadata:
     name: jupyter-notebook
     namespace: namespace
   spec:
     containers:
     - name: minimal-notebook
       image: jupyter/all-spark-notebook:lab-3.1.4 # open source image 
       ports:
       - containerPort: 8888
       command: ["start-notebook.sh"]
       args: ["--LabApp.token=''"]
       env:
       - name: JUPYTER_ENABLE_LAB
         value: "yes"
       - name: KERNEL_LAUNCH_TIMEOUT
         value: "400"
       - name: JUPYTER_GATEWAY_URL
         value: "serverUrl"
       - name: JUPYTER_GATEWAY_VALIDATE_CERT
         value: "false"
       - name: JUPYTER_GATEWAY_AUTH_TOKEN
         value: "session-token"
   ```

   Jupyter Notebook을 FarGate 전용 클러스터에 배포하는 경우 다음 예제와 같이 Jupyter 포드에 `role` 레이블을 지정합니다.

   ```
   ...
   metadata:
     name: jupyter-notebook
     namespace: default
     labels:
       role: example-role-name-label
   spec:
               ...
   ```  
**`namespace`**  
노트북을 배포할 Kubernetes 네임스페이스.  
**`serverUrl`**  
[대화형 엔드포인트의 게이트웨이 서버 URL 검색](#managed-endpoints-self-hosted-gateway)에서 `describe-managed-endpoint` 명령이 반환한 `serverUrl` 속성.  
**`session-token`**  
[인증 토큰을 검색하여 대화형 엔드포인트에 연결](#managed-endpoints-self-hosted-auth)에서 `get-managed-endpoint-session-credentials` 명령이 반환한 `session-token` 속성.  
**`KERNEL_LAUNCH_TIMEOUT`**  
커널이 **RUNNING** 상태가 될 때까지 대화형 엔드포인트가 기다리는 시간(초). 커널 시작 제한 시간을 적절한 값(최대 400초)으로 설정하여 커널 시작이 완료될 때까지 충분한 시간을 확보합니다.  
**`KERNEL_EXTRA_SPARK_OPTS`**  
선택적으로 Spark 커널에 대한 추가 Spark 구성을 전달할 수 있습니다. 다음 예제에서와 같이 Spark 구성 속성으로 값을 포함하는 이 환경 변수를 설정합니다.  

   ```
   - name: KERNEL_EXTRA_SPARK_OPTS
     value: "--conf spark.driver.cores=2
             --conf spark.driver.memory=2G
             --conf spark.executor.instances=2
             --conf spark.executor.cores=2
             --conf spark.executor.memory=2G
             --conf spark.dynamicAllocation.enabled=true
             --conf spark.dynamicAllocation.shuffleTracking.enabled=true
             --conf spark.dynamicAllocation.minExecutors=1
             --conf spark.dynamicAllocation.maxExecutors=5
             --conf spark.dynamicAllocation.initialExecutors=1
             "
   ```

1. Amazon EKS 클러스터에 포드 사양을 배포합니다.

   ```
   kubectl apply -f notebook.yaml -n namespace
   ```

   그러면 Amazon EMR on EKS 대화형 엔드포인트에 연결된 최소 JupyterLab Notebook이 시작됩니다. 포드가 **RUNNING** 상태가 될 때까지 기다립니다. 다음 명령을 실행하여 상태를 확인할 수 있습니다.

   ```
   kubectl get pod jupyter-notebook -n namespace
   ```

   포드가 준비되면 `get pod` 명령은 다음과 비슷한 출력을 반환합니다.

   ```
   NAME              READY  STATUS   RESTARTS  AGE
   jupyter-notebook  1/1    Running  0         46s
   ```

1. 노트북 보안 그룹을 노트북이 예약된 노드에 연결합니다.

   1. 먼저 `describe pod` 명령을 사용하여 `jupyter-notebook` 포드가 예약된 노드를 식별합니다.

      ```
      kubectl describe pod jupyter-notebook -n namespace
      ```

   1. [https://console.aws.amazon.com/eks/home\$1/clusters](https://console.aws.amazon.com/eks/home#/clusters)에서 Amazon EKS 콘솔을 엽니다.

   1. Amazon EKS 클러스터의 **컴퓨팅** 탭으로 이동하여 `describe pod` 명령으로 식별되는 노드를 선택합니다. 노드의 인스턴스 ID를 선택합니다.

   1. **작업** 메뉴에서 **보안** > **보안 그룹 변경**을 선택하여 [보안 그룹 생성](#managed-endpoints-self-hosted-security)에서 생성한 보안 그룹을 연결합니다.

   1. Jupyter 노트북 포드를 배포[]()하는 경우 역할 레이블을 사용하여 Jupyter 노트북 포드에 적용할를 AWS Fargate생성합니다.

      ```
      cat >my-security-group-policy.yaml <<EOF
      apiVersion: vpcresources.k8s.aws/v1beta1
      kind: SecurityGroupPolicy
      metadata:
        name: example-security-group-policy-name
        namespace: default
      spec:
        podSelector:
          matchLabels:
            role: example-role-name-label
        securityGroups:
          groupIds:
            - your-notebook-security-group-id
      EOF
      ```

1. 이제 JupyterLab 인터페이스에 로컬로 액세스할 수 있도록 포트 전달을 수행합니다.

   ```
   kubectl port-forward jupyter-notebook 8888:8888 -n namespace
   ```

   실행이 완료되면 로컬 브라우저로 이동하여 `localhost:8888`에서 JupyterLab 인터페이스를 확인합니다.  
![\[JupyterLab 시작 화면 스크린샷.\]](http://docs.aws.amazon.com/ko_kr/emr/latest/EMR-on-EKS-DevelopmentGuide/images/emr-on-eks-Jupyter-notebook-start.png)

1. JupyterLab에서 새로운 Scala 노트북을 생성합니다. 다음은 Pi 값의 근사치를 구하기 위해 실행할 수 있는 샘플 코드 스니펫입니다.

   ```
   import scala.math.random
   import org.apache.spark.sql.SparkSession
   
   /** Computes an approximation to pi */
   val session = SparkSession
     .builder
     .appName("Spark Pi")
     .getOrCreate()
   
   val slices = 2
   // avoid overflow
   val n = math.min(100000L * slices, Int.MaxValue).toInt 
    
   val count = session.sparkContext
   .parallelize(1 until n, slices)
   .map { i =>
     val x = random * 2 - 1
     val y = random * 2 - 1
     if (x*x + y*y <= 1) 1 else 0
   }.reduce(_ + _)
   
   println(s"Pi is roughly ${4.0 * count / (n - 1)}")
   session.stop()
   ```  
![\[JupyterLab의 예제 Scala 노트북 코드 스크린샷.\]](http://docs.aws.amazon.com/ko_kr/emr/latest/EMR-on-EKS-DevelopmentGuide/images/emr-on-eks-Jupyter-notebook-scala-program.png)

## 자체 호스팅 Jupyter Notebook 삭제
<a name="managed-endpoints-self-hosted-cleanup"></a>

자체 호스팅 노트북을 삭제할 준비가 되면 대화형 엔드포인트와 보안 그룹도 삭제할 수 있습니다. 다음 순서대로 작업을 수행합니다.

1. 다음 명령을 사용하여 `jupyter-notebook` 포드를 삭제합니다.

   ```
   kubectl delete pod jupyter-notebook -n namespace
   ```

1. 그런 다음 `delete-managed-endpoint` 명령을 사용하여 대화형 엔드포인트를 삭제합니다. 대화형 엔드포인트를 삭제하는 단계는 [대화형 엔드포인트 삭제](delete-managed-endpoint.md) 섹션을 참조하세요. 처음에는 엔드포인트가 **TERMINATING** 상태가 됩니다. 모든 리소스가 정리되면 **TERMINATED** 상태로 전환됩니다.

1. [보안 그룹 생성](#managed-endpoints-self-hosted-security)에서 생성한 노트북 보안 그룹을 다른 Jupyter Notebook 배포에 사용할 계획이 없다면 삭제할 수 있습니다. 자세한 내용은 Amazon EC2 사용 설명서에서 [보안 그룹 삭제](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/working-with-security-groups.html#deleting-security-group)를 참조하세요.