클러스터 만들기

Dataproc 클러스터 만드는 방법

요구사항

  • 이름: 클러스터는 소문자로 시작해야 하며 이어서 최대 51자의 소문자, 숫자, 하이픈이 와야 하고, 하이픈으로 끝나서는 안 됩니다.

  • 클러스터 리전: us-east1 또는 europe-west1과 같은 클러스터의 Compute Engine 리전을 지정하여 해당 리전 내에서 VM 인스턴스 및 Cloud Storage에 저장된 클러스터 메타데이터와 같은 클러스터 리소스를 격리해야 합니다.

    • 리전 엔드포인트에 대한 자세한 내용은 리전 엔드포인트를 참조하세요.
    • 리전 선택에 대한 자세한 내용은 사용 가능한 리전 및 영역을 참조하세요. 또한 gcloud compute regions list 명령어를 실행하여 사용 가능한 리전 목록을 표시할 수도 있습니다.
  • 연결: Dataproc 클러스터에서 마스터 및 작업자 VM으로 구성된 Compute Engine 가상 머신 인스턴스에는 전체 내부 IP 네트워킹 교차 연결이 필요합니다. default VPC 네트워크에서 이 연결을 제공합니다(Dataproc 클러스터 네트워크 구성 참조).

gcloud

명령줄에 Dataproc 클러스터를 만들려면 gcloud dataproc clusters create 명령어를 터미널 창에서 로컬로 실행하거나 Cloud Shell에서 실행합니다.

gcloud dataproc clusters create CLUSTER_NAME \
    --region=REGION

명령어는 마스터 및 작업자 가상 머신 인스턴스, 디스크 크기 및 유형, 네트워크 유형, 클러스터가 배포되는 리전 및 영역, 기타 클러스터 설정에 대해 기본 Dataproc 서비스 설정을 사용하여 클러스터를 만듭니다. 명령줄 플래그를 사용하여 클러스터 설정을 맞춤설정하는 방법은 gcloud dataproc clusters create 명령을 참조하세요.

YAML 파일로 클러스터 만들기

  1. 다음 gcloud 명령어를 실행하여 기존 Dataproc 클러스터의 구성을 cluster.yaml 파일로 내보냅니다.
    gcloud dataproc clusters export EXISTING_CLUSTER_NAME \
        --region=REGION \
        --destination=cluster.yaml
    
  2. YAML 파일 구성을 가져와서 새 클러스터를 만듭니다.
    gcloud dataproc clusters import NEW_CLUSTER_NAME \
        --region=REGION \
        --source=cluster.yaml
    

참고: 내보내기 작업 중에 클러스터 관련 필드(예: 클러스터 이름), 출력 전용 필드, 자동으로 적용되는 라벨이 필터링됩니다. 클러스터를 만들 때 사용하는 가져온 YAML 파일에는 이러한 필드가 허용되지 않습니다.

REST

이 섹션에서는 필수 값과 기본 구성(마스터 1개, 작업자 2개)을 가진 클러스터를 만드는 방법을 보여줍니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project-id: Google Cloud 프로젝트 ID
  • region: 클러스터 리전
  • clusterName: 클러스터 이름

HTTP 메서드 및 URL:

POST https://dataproc.googleapis.com/v1/projects/project-id/regions/region/clusters

JSON 요청 본문:

{
  "clusterName": "cluster-name",
  "config": {}
}

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
"name": "projects/project-id/regions/region/operations/b5706e31......",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.dataproc.v1.ClusterOperationMetadata",
    "clusterName": "cluster-name",
    "clusterUuid": "5fe882b2-...",
    "status": {
      "state": "PENDING",
      "innerState": "PENDING",
      "stateStartTime": "2019-11-21T00:37:56.220Z"
    },
    "operationType": "CREATE",
    "description": "Create cluster with 2 workers",
    "warnings": [
      "For PD-Standard without local SSDs, we strongly recommend provisioning 1TB ...""
    ]
  }
}

콘솔

브라우저의 Google Cloud 콘솔에서 Dataproc 클러스터 만들기 페이지를 열고 Compute Engine에서 Dataproc 클러스터 만들기 페이지의 Compute Engine 행에 있는 클러스터에서 만들기를 클릭합니다. 클러스터 설정 패널은 기본값으로 채워진 필드로 선택됩니다. 각 패널을 선택하고 기본값을 확인하거나 변경하여 클러스터를 맞춤설정할 수 있습니다.

만들기를 클릭하여 클러스터를 만듭니다. 클러스터가 프로비저닝되면 클러스터 이름이 클러스터 페이지에 표시되고 상태가 실행 중으로 업데이트됩니다. 클러스터 이름을 클릭하여 클러스터의 작업, 인스턴스, 구성 설정을 검사하고 클러스터에서 실행되는 웹 인터페이스에 연결할 수 있는 클러스터 세부정보 페이지를 엽니다.

Go

  1. 클라이언트 라이브러리를 설치합니다.
  2. 애플리케이션 기본 사용자 인증 정보 설정
  3. 코드를 실행합니다.
    import (
    	"context"
    	"fmt"
    	"io"
    
    	dataproc "cloud.google.com/go/dataproc/apiv1"
    	"cloud.google.com/go/dataproc/apiv1/dataprocpb"
    	"google.golang.org/api/option"
    )
    
    func createCluster(w io.Writer, projectID, region, clusterName string) error {
    	// projectID := "your-project-id"
    	// region := "us-central1"
    	// clusterName := "your-cluster"
    	ctx := context.Background()
    
    	// Create the cluster client.
    	endpoint := region + "-dataproc.googleapis.com:443"
    	clusterClient, err := dataproc.NewClusterControllerClient(ctx, option.WithEndpoint(endpoint))
    	if err != nil {
    		return fmt.Errorf("dataproc.NewClusterControllerClient: %w", err)
    	}
    	defer clusterClient.Close()
    
    	// Create the cluster config.
    	req := &dataprocpb.CreateClusterRequest{
    		ProjectId: projectID,
    		Region:    region,
    		Cluster: &dataprocpb.Cluster{
    			ProjectId:   projectID,
    			ClusterName: clusterName,
    			Config: &dataprocpb.ClusterConfig{
    				MasterConfig: &dataprocpb.InstanceGroupConfig{
    					NumInstances:   1,
    					MachineTypeUri: "n1-standard-2",
    				},
    				WorkerConfig: &dataprocpb.InstanceGroupConfig{
    					NumInstances:   2,
    					MachineTypeUri: "n1-standard-2",
    				},
    			},
    		},
    	}
    
    	// Create the cluster.
    	op, err := clusterClient.CreateCluster(ctx, req)
    	if err != nil {
    		return fmt.Errorf("CreateCluster: %w", err)
    	}
    
    	resp, err := op.Wait(ctx)
    	if err != nil {
    		return fmt.Errorf("CreateCluster.Wait: %w", err)
    	}
    
    	// Output a success message.
    	fmt.Fprintf(w, "Cluster created successfully: %s", resp.ClusterName)
    	return nil
    }
    

Java

  1. 클라이언트 라이브러리를 설치합니다.
  2. 애플리케이션 기본 사용자 인증 정보 설정
  3. 코드를 실행합니다.
    import com.google.api.gax.longrunning.OperationFuture;
    import com.google.cloud.dataproc.v1.Cluster;
    import com.google.cloud.dataproc.v1.ClusterConfig;
    import com.google.cloud.dataproc.v1.ClusterControllerClient;
    import com.google.cloud.dataproc.v1.ClusterControllerSettings;
    import com.google.cloud.dataproc.v1.ClusterOperationMetadata;
    import com.google.cloud.dataproc.v1.InstanceGroupConfig;
    import java.io.IOException;
    import java.util.concurrent.ExecutionException;
    
    public class CreateCluster {
    
      public static void createCluster() throws IOException, InterruptedException {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "your-project-id";
        String region = "your-project-region";
        String clusterName = "your-cluster-name";
        createCluster(projectId, region, clusterName);
      }
    
      public static void createCluster(String projectId, String region, String clusterName)
          throws IOException, InterruptedException {
        String myEndpoint = String.format("%s-dataproc.googleapis.com:443", region);
    
        // Configure the settings for the cluster controller client.
        ClusterControllerSettings clusterControllerSettings =
            ClusterControllerSettings.newBuilder().setEndpoint(myEndpoint).build();
    
        // Create a cluster controller client with the configured settings. The client only needs to be
        // created once and can be reused for multiple requests. Using a try-with-resources
        // closes the client, but this can also be done manually with the .close() method.
        try (ClusterControllerClient clusterControllerClient =
            ClusterControllerClient.create(clusterControllerSettings)) {
          // Configure the settings for our cluster.
          InstanceGroupConfig masterConfig =
              InstanceGroupConfig.newBuilder()
                  .setMachineTypeUri("n1-standard-2")
                  .setNumInstances(1)
                  .build();
          InstanceGroupConfig workerConfig =
              InstanceGroupConfig.newBuilder()
                  .setMachineTypeUri("n1-standard-2")
                  .setNumInstances(2)
                  .build();
          ClusterConfig clusterConfig =
              ClusterConfig.newBuilder()
                  .setMasterConfig(masterConfig)
                  .setWorkerConfig(workerConfig)
                  .build();
          // Create the cluster object with the desired cluster config.
          Cluster cluster =
              Cluster.newBuilder().setClusterName(clusterName).setConfig(clusterConfig).build();
    
          // Create the Cloud Dataproc cluster.
          OperationFuture<Cluster, ClusterOperationMetadata> createClusterAsyncRequest =
              clusterControllerClient.createClusterAsync(projectId, region, cluster);
          Cluster response = createClusterAsyncRequest.get();
    
          // Print out a success message.
          System.out.printf("Cluster created successfully: %s", response.getClusterName());
    
        } catch (ExecutionException e) {
          System.err.println(String.format("Error executing createCluster: %s ", e.getMessage()));
        }
      }
    }

Node.js

  1. 클라이언트 라이브러리를 설치합니다.
  2. 애플리케이션 기본 사용자 인증 정보 설정
  3. 코드를 실행합니다.
    const dataproc = require('@google-cloud/dataproc');
    
    // TODO(developer): Uncomment and set the following variables
    // projectId = 'YOUR_PROJECT_ID'
    // region = 'YOUR_CLUSTER_REGION'
    // clusterName = 'YOUR_CLUSTER_NAME'
    
    // Create a client with the endpoint set to the desired cluster region
    const client = new dataproc.v1.ClusterControllerClient({
      apiEndpoint: `${region}-dataproc.googleapis.com`,
      projectId: projectId,
    });
    
    async function createCluster() {
      // Create the cluster config
      const request = {
        projectId: projectId,
        region: region,
        cluster: {
          clusterName: clusterName,
          config: {
            masterConfig: {
              numInstances: 1,
              machineTypeUri: 'n1-standard-2',
            },
            workerConfig: {
              numInstances: 2,
              machineTypeUri: 'n1-standard-2',
            },
          },
        },
      };
    
      // Create the cluster
      const [operation] = await client.createCluster(request);
      const [response] = await operation.promise();
    
      // Output a success message
      console.log(`Cluster created successfully: ${response.clusterName}`);

Python

  1. 클라이언트 라이브러리를 설치합니다.
  2. 애플리케이션 기본 사용자 인증 정보 설정
  3. 코드를 실행합니다.
    from google.cloud import dataproc_v1 as dataproc
    
    def create_cluster(project_id, region, cluster_name):
        """This sample walks a user through creating a Cloud Dataproc cluster
        using the Python client library.
    
        Args:
            project_id (string): Project to use for creating resources.
            region (string): Region where the resources should live.
            cluster_name (string): Name to use for creating a cluster.
        """
    
        # Create a client with the endpoint set to the desired cluster region.
        cluster_client = dataproc.ClusterControllerClient(
            client_options={"api_endpoint": f"{region}-dataproc.googleapis.com:443"}
        )
    
        # Create the cluster config.
        cluster = {
            "project_id": project_id,
            "cluster_name": cluster_name,
            "config": {
                "master_config": {"num_instances": 1, "machine_type_uri": "n1-standard-2"},
                "worker_config": {"num_instances": 2, "machine_type_uri": "n1-standard-2"},
            },
        }
    
        # Create the cluster.
        operation = cluster_client.create_cluster(
            request={"project_id": project_id, "region": region, "cluster": cluster}
        )
        result = operation.result()
    
        # Output a success message.
        print(f"Cluster created successfully: {result.cluster_name}")