이 가이드에서는 웹 애플리케이션을 Docker 컨테이너 이미지로 패키징하고 해당 컨테이너 이미지를 Google Kubernetes Engine(GKE) 클러스터에서 실행하는 방법을 보여줍니다. 그런 다음 웹 애플리케이션을 사용자의 요구 사항에 맞게 확장할 수 있는 부하 분산된 복제본 집합으로 배포합니다. ## 목표 - 샘플 웹 애플리케이션을 Docker 이미지로 패키징 - Artifact Registry에 Docker 이미지 업로드 - GKE 클러스터 만들기 - 샘플 앱을 클러스터에 배포 - 배포를 위한 자동 확장 관리 - 샘플 앱을 인터넷에 노출 - 샘플 앱의 새 버전 배포 ## 비용 이 가이드에서는 청구 가능한 다음 Google Cloud 구성요소를 사용합니다. 예상 사용량을 기반으로 비용 견적을 생성하려면 가격 계산기 사용 이 자습서를 마치면 생성한 리소스를 삭제하여 계속 청구되지 않도록 할 수 있습니다. 자세한 내용은 정리를 참조하세요. ## 시작하기 전에 Kubernetes Engine API를 사용 설정하려면 다음 단계를 따르세요. - Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들어 실제 시나리오에서 Google 제품의 성능을 평가하세요. 신규 고객은 또한 워크로드를 실행, 테스트 및 배포할 수 있는 $300의 무료 크레딧을 받습니다. - Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다. - 클라우드 프로젝트에 결제가 사용 설정되어 있는지 확인하세요. 프로젝트에서 결제가 사용 설정되었는지 확인하는 방법 알아보기 - Artifact Registry 및 Google Kubernetes Engine API 사용 설정 - Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다. - 클라우드 프로젝트에 결제가 사용 설정되어 있는지 확인하세요. 프로젝트에서 결제가 사용 설정되었는지 확인하는 방법 알아보기 - Artifact Registry 및 Google Kubernetes Engine API 사용 설정 옵션 A: Cloud Shell 사용 함께 제공되는 Cloud Shell을 사용하여 이 가이드를 따를 수 있습니다. 사전 설치된 gcloud, 도커 및 사용된 kubectl 명령줄 도구 이 튜토리얼에서. Cloud Shell을 사용하는 경우 다음을 설치할 필요가 없습니다. 워크스테이션의 명령줄 도구 Cloud Shell을 사용하려면: - Google 클라우드 콘솔로 이동 클릭 Cloud Shell 활성화 Google Cloud Console 창 상단의 버튼 Google Cloud Console 하단의 새 프레임 내에서 Cloud Shell 세션이 열리고 명령줄 프롬프트가 표시됩니다. 옵션 B: 로컬에서 명령줄 도구 사용 워크스테이션에서 이 자습서를 따르려는 경우 다음 단계에 따라 필요한 도구를 설치하십시오. Google 클라우드 CLI 설치 gcloud CLI를 사용하여 Kubernetes 명령줄 도구를 설치합니다. GKE 클러스터의 클러스터 오케스트레이션 시스템인 Kubernetes와 통신하는 데 사용되는 kubectlis: gcloud 구성요소 설치 kubectl 워크스테이션에 Docker Community Edition(CE)을 설치합니다. 이를 사용하여 애플리케이션의 컨테이너 이미지를 빌드합니다. Git 소스 제어 도구를 설치하여 GitHub에서 샘플 애플리케이션을 가져옵니다. ## 저장소 생성 이 가이드에서는 Artifact Registry에 이미지를 저장하고 배포합니다. 레지스트리에서. Artifact Registry는 권장되는 컨테이너 레지스트리입니다. 구글 클라우드. 이 빠른 시작에서는 다음과 같은 리포지토리를 만듭니다. 안녕하세요 레포 설정 PROJECT_ID환경 변수를 Google Cloud 프로젝트 ID( ). 컨테이너 이미지를 빌드하고 리포지토리에 푸시할 때 이 환경 변수를 사용합니다. 프로젝트_ID 내보내기 PROJECT_ID= 프로젝트_ID 확인 PROJECT_IDenvironment 변수에 올바른 값이 있습니다. 에코 $PROJECT_ID Google Cloud CLI의 프로젝트 ID를 설정합니다. gcloud 구성 설정 프로젝트 $PROJECT_ID 산출: 업데이트된 속성[코어/프로젝트] 만들기 다음 명령을 사용하여 hello-reporepository: gcloud artifacts repositories create hello-repo \ --repository-format=docker \ --location= REGION\ --description="도커 리포지토리"바꾸다 다음과 같은 리포지토리의 영역으로 지역 미국 서부1. 사용 가능한 위치 목록을 보려면 다음 명령을 실행하십시오. gcloud 아티팩트 위치 목록 ## 컨테이너 이미지 빌드 이 자습서에서는 샘플 웹을 배포합니다. 호출된 애플리케이션 작성된 웹 서버인 hello-app 메시지로 모든 요청에 ​​응답하는 Go에서 안녕, 세계! 포트 8080에서 GKE는 Docker 이미지를 애플리케이션 배포 형식으로 허용합니다. 배포하기 전에 hello-app to GKE, 패키징해야 함 그만큼 Docker 이미지로 된 hello-app 소스 코드 Docker 이미지를 빌드하려면 소스 코드와 Dockerfile이 필요합니다. Dockerfile에는 이미지 빌드 방법에 대한 지침이 포함되어 있습니다. 다운로드 다음 명령을 실행하여 hello-appsource 코드 및 Dockerfile: 자식 클론 httpsgithub.com/GoogleCloudPlatform/kubernetes-engine-samples cd kubernetes-engine-samples/hello-app 다음에 대한 Docker 이미지 빌드 및 태그 지정 안녕하세요 앱: 도커 빌드 -t REGION-docker.pkg.devPROJECT_ID}/hello-repo/hello-app:v1 이 명령은 Docker가 다음을 사용하여 이미지를 빌드하도록 지시합니다. 현재 디렉터리에 있는 Dockerfile을 로컬 환경에 저장하고 다음과 같은 이름으로 태그를 지정합니다. us-west1-docker.pkg.dev/my-project/hello-repo/hello-app:v1. 이미지는 다음 섹션에서 Artifact Registry로 푸시됩니다. - PROJECT_IDvariable은 컨테이너 이미지를 Google Cloud 프로젝트의 hello-repository - us-west1-docker.pkg.devprefix는 저장소의 지역 호스트인 Artifact Registry를 나타냅니다. - 실행 docker imagescommand를 사용하여 빌드가 성공했는지 확인합니다. 도커 이미지 산출: 리포지토리 태그 이미지 ID 생성 크기 us-west1-docker.pkg.dev/my-project/hello-repo/hello-app v1 25cfadb1bf28 10초 전 54MB ## 컨테이너를 로컬에서 실행(선택사항) 로컬 Docker 엔진을 사용하여 컨테이너 이미지를 테스트합니다. 도커 실행 --rm -p 8080:8080 REGION-docker.pkg.devPROJECT_ID}/hello-repo/hello-app:v1 Cloud Shell을 사용하는 경우 웹 미리보기 버튼 그런 다음 8080포트 번호. GKE는 새 브라우저 창에서 프록시 서비스의 미리보기 URL을 엽니다. 그렇지 않으면 새 터미널 창(또는 Cloud Shell 탭)을 열고 다음 명령을 실행하여 컨테이너가 작동하는지 확인하고 "Hello, World"로 요청에 응답합니다. 컬 httplocalhost:8080 성공적인 응답을 본 후 다음을 눌러 컨테이너를 종료할 수 있습니다. Ctrl+C 탭에서 docker runcommand가 실행 중입니다. ## Docker 이미지를 Artifact Registry로 푸시 GKE 클러스터가 컨테이너 이미지를 다운로드하고 실행할 수 있도록 컨테이너 이미지를 레지스트리에 업로드해야 합니다. 이 가이드에서는 컨테이너를 Artifact Registry에 저장합니다. Artifact Registry에 인증하도록 Docker 명령줄 도구를 구성합니다. gcloud 인증 구성 도커 지역-docker.pkg.dev 방금 빌드한 Docker 이미지를 리포지토리에 푸시합니다. 도커 푸시 REGION-docker.pkg.devPROJECT_ID}/hello-repo/hello-app:v1 ## GKE 클러스터 만들기 이제 Docker 이미지가 Artifact Registry에 저장되었으므로 GKE를 만듭니다. 무리 달리다 안녕하세요 앱. GKE 클러스터는 Compute Engine VM 인스턴스의 풀로 구성됩니다. 오픈 소스 클러스터 오케스트레이션인 Kubernetes 실행 GKE를 지원하는 시스템 클라우드 쉘 Compute Engine 영역 또는 지역을 설정합니다. GKE에서 사용하기로 선택한 작업 모드에 따라 기본 영역 또는 리전을 지정합니다. 표준 모드를 ​​사용하는 경우 클러스터는 영역(이 자습서의 경우)이므로 기본 컴퓨팅 영역을 설정합니다. Autopilot 모드를 사용하는 경우 클러스터는 지역이므로 기본 컴퓨팅 지역을 설정합니다. 생성한 Artifact Registry 저장소에 가장 가까운 영역 또는 지역을 선택하세요. 다음과 같은 Standardcluster us-west1-a: gcloud config set 컴퓨팅/영역 COMPUTE_ZONE Autopilotcluster, 예: 미국 서부1: gcloud config set 컴퓨팅/지역 COMPUTE_REGION - 이름이 지정된 클러스터 만들기 안녕하세요 클러스터: 표준 클러스터: gcloud 컨테이너 클러스터는 hello-cluster를 만듭니다. 오토파일럿 클러스터: gcloud 컨테이너 클러스터 create-auto hello-cluster GKE 클러스터가 생성되고 상태를 확인하는 데 몇 분 정도 걸립니다. - 명령이 완료되면 다음 명령을 실행하여 클러스터의 3개 노드를 확인합니다. kubectl 노드 가져오기 산출: 이름 상태 역할 연령 버전 gke-hello-cluster-default-pool-229c0700-cbtd Ready 92s v1.18.12-gke.1210 gke-hello-cluster-default-pool-229c0700-fc5j Ready 91s v1.18.12-gke.1210 gke-hello-cluster-default-pool-229c0700-n9l7 Ready 92s v1.18.12-gke.1210 Console Go to the Google Kubernetes Enginepage in the Google Cloud console Go to Google Kubernetes Engine Click Create Choose Standard or Autopilot mode and click Configure In the Namefield, enter the name hello-cluster Select a zone or region: Standardcluster: Under Location type, select Zonaland then select a Compute Engine zone from the Zonedrop-down list, such as us-west1-a Autopilotcluster: Select a Compute Engine region from the Regiondrop-down list, such as us-west1 - Click Create. This creates a GKE cluster Wait for the cluster to be created. When the cluster is ready, a green check mark appears next to the cluster name ## Deploying the sample app to GKE You are now ready to deploy the Docker image you built to your GKE cluster Kubernetes represents applications as Pods, which are scalable units holding one or more containers. The Pod is the smallest deployable unit in Kubernetes. Usually, you deploy Pods as a set of replicas that can be scaled and distributed together across your cluster. One way to deploy a set of replicas is through a Kubernetes Deployment In this section, you create a Kubernetes Deployment to run hello-app on your cluster. This Deployment has replicas (Pods). One Deployment Pod contains only one container: the hello-app Docker image You also create a HorizontalPodAutoscaler resource that scales the number of Pods from 3 to a number between 1 and 5, based on CPU load Cloud Shell Ensure that you are connected to your GKE cluster gcloud container clusters get-credentials hello-cluster --zone COMPUTE_ZONE Create a Kubernetes Deployment for your hello-appDocker image kubectl create deployment hello-app --image= REGION-docker.pkg.devPROJECT_ID}/hello-repo/hello-app:v1 Set the baseline number of Deployment replicas to 3 kubectl scale deployment hello-app --replicas=3 Create a HorizontalPodAutoscalerresource for your Deployment kubectl autoscale deployment hello-app --cpu-percent=80 --min=1 --max=5 To see the Pods created, run the following command: kubectl get pods Output: NAME READY STATUS RESTARTS AGE hello-app-784d7569bc-hgmpx 1/1 Running 0 10s hello-app-784d7569bc-jfkz5 1/1 Running 0 10s hello-app-784d7569bc-mnrrl 1/1 Running 0 15s Console Go to the Workloadspage in the Google Cloud console Click Deploy In the Specify containersection, select Existing container image In the Image pathfield, click Select In the Select container imagepane, select the hello-appimage you pushed to Artifact Registry and click Select In the Containersection, click Done, then click Continue In the Configurationsection, under Labels, enter appfor Keyand hello-appfor Value Under Configuration YAML, click View YAML. This opens a YAML configuration file representing the two Kubernetes API resources about to be deployed into your cluster: one Deployment, and one HorizontalPodAutoscalerfor that Deployment Click Close, then click Deploy When the Deployment Pods are ready, the Deployment detailspage opens Under Managed pods, note the three running Pods for the hello-appDeployment ## Exposing the sample app to the internet While Pods do have individually-assigned IP addresses, those IPs can only be reached from inside your cluster. Also, GKE Pods are designed to be ephemeral, starting or stopping based on scaling needs. And when a Pod crashes due to an error, GKE automatically redeploys that Pod, assigning a new Pod IP address each time What this means is that for any Deployment, the set of IP addresses corresponding to the active set of Pods is dynamic. We need a way to 1) group Pods together into one static hostname, and 2) expose a group of Pods outside the cluster, to the internet Kubernetes Services solve for both of these problems Services group Pods into one static IP address, reachable from any Pod inside the cluster GKE also assigns a DNS hostname to that static IP. For example, hello-app.default.svc.cluster.local The default Service type in GKE is called ClusterIP, where the Service gets an IP address reachable only from inside the cluster To expose a Kubernetes Service outside the cluster, create a Service of type LoadBalancer This type of Service spawns an External Load Balancer IP for a set of Pods, reachable through the internet In this section, you expose the hello-app Deployment to the internet using a Service of type LoadBalancer Cloud Shell Use the kubectl exposecommand to generate a Kubernetes Service for the hello-appdeployment: kubectl expose deployment hello-app --name=hello-app-service --type=LoadBalancer --port 80 --target-port 8080 Here, the --portflag specifies the port number configured on the Load Balancer, and the --target-portflag specifies the port number that the hello-appcontainer is listening on Run the following command to get the Service details for hello-app-service: kubectl get service Output: NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE hello-app-service 10.3.251.122 203.0.113.0 80:30877/TCP 10s Copy the EXTERNAL_IPaddress to the clipboard (for instance: 203.0.113.0) Console Go to the Workloadspage in the Google Cloud console Click hello-app From the Deployment details page, click Actions > Expose In the Exposedialog, set the Target portto 8080. This is the port the hello-appcontainer listens on From the Service typedrop-down list, select Load balancer Click Exposeto create a Kubernetes Service for hello-app When the Load Balancer is ready, the Service detailspage opens Scroll down to the External endpointsfield, and copy the IP address Now that the hello-app Pods are exposed to the internet through a Kubernetes Service, you can open a new browser tab, and navigate to the Service IP address you copied to the clipboard. A Hello, World! message appears, along with a Hostname field. The Hostname corresponds to one of the three hello-app Pods serving your HTTP request to your browser ## Deploying a new version of the sample app In this section, you upgrade hello-app to a new version by building and deploying a new Docker image to your GKE cluster GKE's rolling update feature lets you update your Deployments without downtime. During a rolling update, your GKE cluster incrementally replaces the existing hello-app Pods with Pods containing the Docker image for the new version During the update, your load balancer service routes traffic only into available Pods Return to Cloud Shell, where you have cloned the hello app source code and Dockerfile. Update the function hello()in the main.gofile to report the new version 2.0.0 Build and tag a new hello-appDocker image docker build -t REGION-docker.pkg.devPROJECT_ID}/hello-repo/hello-app:v2 Push the image to Artifact Registry docker push REGION-docker.pkg.devPROJECT_ID}/hello-repo/hello-app:v2 Now you're ready to update your hello-app Kubernetes Deployment to use a new Docker image Cloud Shell Apply a rolling update to the existing hello-appDeployment with an image update using the kubectl set imagecommand: kubectl set image deployment/hello-app hello-app= REGION-docker.pkg.devPROJECT_ID}/hello-repo/hello-app:v2 Watch the running Pods running the v1image stop, and new Pods running the v2image start watch kubectl get pods Output: NAME READY STATUS RESTARTS AGE hello-app-89dc45f48-5bzqp 1/1 Running 0 2m42s hello-app-89dc45f48-scm66 1/1 Running 0 2m40s In a separate tab, navigate again to the hello-app-serviceExternal IP. You should now see the Versionset to 2.0.0 Console Go to the Workloadspage in the Google Cloud console Click hello-app On the Deployment detailspage, click Actions > Rolling update In the Rolling updatedialog, set the Image of hello-appfield to REGION-docker.pkg.dev/ PROJECT_ID/hello-repo/hello-app:v2 Click Update On the Deployment detailspage, inspect the Active Revisionssection. You should now see two Revisions, 1 and 2. Revision 1 corresponds to the initial Deployment you created earlier. Revision 2 is the rolling update you just started After a few moments, refresh the page. Under Managed pods, all of the replicas of hello-appnow correspond to Revision 2 In a separate tab, navigate again to the Service IP address you copied. The Versionshould be 2.0.0 ## Clean up To avoid incurring charges to your Google Cloud account for the resources used in this tutorial, either delete the project that contains the resources, or keep the project and delete the individual resources Delete the Service:This deallocates the Cloud Load Balancer created for your Service: kubectl delete service hello-app-service Delete the cluster:This deletes the resources that make up the cluster, such as the compute instances, disks, and network resources: gcloud container clusters delete hello-cluster --zone COMPUTE_ZONE Delete your container images:This deletes the Docker images you pushed to Artifact Registry gcloud artifacts docker images delete REGION-docker.pkg.devPROJECT_ID}/hello-repo/hello-app:v1 \ --delete-tags --quiet gcloud artifacts docker images delete \ REGION-docker.pkg.devPROJECT_ID}/hello-repo/hello-app:v2 \ --delete-tags --quiet ## What's next Learn about Pricing for GKE and use the Pricing Calculator to estimate costs Read the Load Balancers tutorial, which demonstrates advanced load balancing configurations for web applications Configure a static IP and domain name for your application Explore other Kubernetes Engine tutorials Explore reference architectures, diagrams, tutorials, and best practices about Google Cloud. Take a look at our Cloud Architecture Center ## Try it for yourself If you're new to Google Cloud, create an account to evaluate how GKE performs in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.Try GKE free