Hướng dẫn này chỉ cho bạn cách đóng gói ứng dụng web trong hình ảnh bộ chứa Docker và chạy hình ảnh bộ chứa đó trên cụm Google Kubernetes Engine (GKE). Sau đó, bạn triển khai ứng dụng web dưới dạng một tập hợp các bản sao cân bằng tải có thể mở rộng theo nhu cầu của người dùng của bạn ## Mục tiêu - Đóng gói ứng dụng web mẫu vào Docker image - Tải hình ảnh Docker lên Artifact Registry - Tạo cụm GKE - Triển khai ứng dụng mẫu cho cụm - Quản lý autoscaling cho việc triển khai - Đưa ứng dụng mẫu lên internet - Triển khai phiên bản mới của ứng dụng mẫu ## Chi phí Hướng dẫn này sử dụng các thành phần có thể thanh toán sau của Google Cloud: Để tạo ước tính chi phí dựa trên mức sử dụng dự kiến ​​của bạn, sử dụng máy tính giá Khi bạn hoàn thành hướng dẫn này, bạn có thể tránh tiếp tục thanh toán bằng cách xóa các tài nguyên bạn đã tạo. Để biết thêm thông tin, hãy xem Dọn dẹp ## Trước khi bạn bắt đầuThực hiện các bước sau để bật API Kubernetes Engine: - Đăng nhập vào tài khoản Google Cloud của bạn. Nếu bạn mới sử dụng Google Cloud, hãy tạo một tài khoản để đánh giá hiệu quả hoạt động của các sản phẩm của chúng tôi trong các tình huống thực tế. Khách hàng mới cũng nhận được 300 đô la tín dụng miễn phí để chạy, thử nghiệm và triển khai khối lượng công việc - Trong bảng điều khiển Google Cloud, trên trang bộ chọn dự án, hãy chọn hoặc tạo một dự án Google Cloud - Đảm bảo rằng thanh toán được bật cho dự án Đám mây của bạn. Tìm hiểu cách kiểm tra xem thanh toán có được bật trên một dự án hay không - Kích hoạt Artifact Registry và Google Kubernetes Engine APIs - Trong bảng điều khiển Google Cloud, trên trang bộ chọn dự án, hãy chọn hoặc tạo một dự án Google Cloud - Đảm bảo rằng thanh toán được bật cho dự án Đám mây của bạn. Tìm hiểu cách kiểm tra xem thanh toán có được bật trên một dự án hay không - Kích hoạt Artifact Registry và Google Kubernetes Engine APIs Tùy chọn A: Sử dụng Cloud Shell Bạn có thể làm theo hướng dẫn này bằng Cloud Shell, đi kèm được cài đặt sẵn với đám mây, docker, và các công cụ dòng lệnh kubectl được sử dụng trong hướng dẫn này. Nếu bạn sử dụng Cloud Shell, bạn không cần cài đặt những thứ này công cụ dòng lệnh trên máy trạm của bạn Để sử dụng Cloud Shell: - Chuyển đến bảng điều khiển Google Cloud Nhấn vào Kích hoạt Cloud Shell nút ở đầu cửa sổ bảng điều khiển Google Cloud Phiên Cloud Shell sẽ mở bên trong một khung mới ở cuối bảng điều khiển Google Cloud và hiển thị lời nhắc dòng lệnh Tùy chọn B: Sử dụng các công cụ dòng lệnh cục bộ Nếu bạn muốn làm theo hướng dẫn này trên máy trạm của mình, hãy làm theo các bước sau để cài đặt các công cụ cần thiết Cài đặt Google Cloud CLI Sử dụng gcloud CLI, cài đặt công cụ dòng lệnh Kubernetes kubectlis được sử dụng để giao tiếp với Kubernetes, là hệ thống điều phối cụm của các cụm GKE: các thành phần gcloud cài đặt kubectl Cài đặt Docker Community Edition (CE) trên máy trạm của bạn. Bạn sử dụng điều này để tạo hình ảnh vùng chứa cho ứng dụng Cài đặt công cụ kiểm soát nguồn Git để tìm nạp ứng dụng mẫu từ GitHub ## Tạo kho lưu trữ Trong hướng dẫn này, bạn lưu trữ một hình ảnh trong Artifact Registry và triển khai nó từ sổ đăng ký. Artifact Registry là cơ quan đăng ký vùng chứa được đề xuất trên Đám mây của Google. Để bắt đầu nhanh này, bạn sẽ tạo một kho lưu trữ có tên xin chào-repo Đặt PROJECT_IDBiến môi trường thành ID dự án Google Cloud của bạn ( ). Bạn sẽ sử dụng biến môi trường này khi xây dựng hình ảnh bộ chứa và đẩy nó vào kho lưu trữ của bạn DỰ ÁN_ID xuất DỰ ÁN_ID = DỰ ÁN_ID Xác nhận rằng PROJECT_IDBiến môi trường có giá trị đúng: tiếng vang $PROJECT_ID Đặt ID dự án của bạn cho Google Cloud CLI: dự án thiết lập cấu hình gcloud $PROJECT_ID Đầu ra: Thuộc tính được cập nhật [lõi/dự án] tạo hello-reporepository bằng lệnh sau: kho lưu trữ hiện vật gcloud tạo hello-repo \ --repository-format=docker \ --location= KHU VỰC\ --description="Kho lưu trữ Docker"Thay thế với một khu vực cho kho lưu trữ, chẳng hạn như KHU VỰC ta-tây1. Để xem danh sách các vị trí khả dụng, hãy chạy lệnh: danh sách vị trí tạo tác gcloud ## Xây dựng hình ảnh vùng chứa Trong hướng dẫn này, bạn triển khai một trang web mẫu ứng dụng gọi là hello-app, một máy chủ web được viết trong Go đáp ứng tất cả các yêu cầu bằng tin nhắn Chào thế giới! trên cổng 8080 GKE chấp nhận hình ảnh Docker làm định dạng triển khai ứng dụng Trước khi triển khai xin chào ứng dụng cho GKE, bạn phải đóng gói các mã nguồn ứng dụng hello dưới dạng hình ảnh Docker Để xây dựng hình ảnh Docker, bạn cần mã nguồn và Dockerfile. Dockerfile chứa các hướng dẫn về cách hình ảnh được tạo Tải về mã hello-appsource và Dockerfile bằng cách chạy các lệnh sau: git clone httpsgithub.com/GoogleCloudPlatform/kubernetes-engine-samples cd kubernetes-engine-samples/hello-app Xây dựng và gắn thẻ hình ảnh Docker cho xin chào-ứng dụng: xây dựng docker -t REGION-docker.pkg.devPROJECT_ID}/hello-repo/hello-app:v1 Lệnh này hướng dẫn Docker xây dựng hình ảnh bằng cách sử dụng Dockerfile trong thư mục hiện tại, lưu nó vào môi trường cục bộ của bạn và gắn thẻ nó với một tên, chẳng hạn như us-west1-docker.pkg.dev/my-project/hello-repo/hello-app:v1. Hình ảnh được đẩy vào Artifact Registry trong phần tiếp theo - Các PROJECT_IDvariable liên kết hình ảnh vùng chứa với hello-reporepository trong dự án Google Cloud của bạn - Các us-west1-docker.pkg.devprefix đề cập đến Cơ quan đăng ký tạo phẩm, máy chủ khu vực cho kho lưu trữ của bạn - Các Chạy docker imagecommand để xác minh rằng quá trình xây dựng đã thành công: hình ảnh docker Đầu ra: ID HÌNH ẢNH THẺ KHO LƯU TRỮ KÍCH THƯỚC TẠO us-west1-docker.pkg.dev/my-project/hello-repo/hello-app v1 25cfadb1bf28 10 giây trước 54 MB ## Chạy cục bộ vùng chứa của bạn (tùy chọn) Kiểm tra hình ảnh bộ chứa của bạn bằng công cụ Docker cục bộ của bạn: docker chạy --rm -p 8080:8080 REGION-docker.pkg.devPROJECT_ID}/hello-repo/hello-app:v1 Nếu bạn đang sử dụng Cloud Shell, hãy nhấp vào nút Nút xem trước trên web và sau đó chọn 8080 số cổng. GKE mở URL xem trước trên dịch vụ proxy của nó trong cửa sổ trình duyệt mới Nếu không, hãy mở một cửa sổ terminal mới (hoặc tab Cloud Shell) và chạy lệnh sau để xác minh rằng vùng chứa hoạt động và phản hồi các yêu cầu với "Xin chào, Thế giới cuộn tròn httplocalhost:8080 Sau khi bạn thấy phản hồi thành công, bạn có thể tắt vùng chứa bằng cách nhấn Ctrl+Cin tab nơi docker runcommand đang chạy ## Đẩy hình ảnh Docker vào Artifact Registry Bạn phải tải hình ảnh bộ chứa lên sổ đăng ký để cụm GKE của bạn có thể tải xuống và chạy hình ảnh bộ chứa. Trong hướng dẫn này, bạn sẽ lưu trữ vùng chứa của mình trong Artifact Registry Định cấu hình công cụ dòng lệnh Docker để xác thực với Artifact Registry: gcloud auth cấu hình-docker KHU VỰC-docker.pkg.dev Đẩy hình ảnh Docker mà bạn vừa tạo vào kho lưu trữ: đẩy docker REGION-docker.pkg.devPROJECT_ID}/hello-repo/hello-app:v1 ## Tạo cụm GKE Giờ đây, hình ảnh Docker được lưu trữ trong Artifact Registry, hãy tạo một GKE cụm chạy xin chào-ứng dụng. Một cụm GKE bao gồm một nhóm các phiên bản máy ảo Compute Engine chạy Kubernetes, dàn nhạc cụm nguồn mở hệ thống cung cấp năng lượng cho GKE vỏ mây Đặt vùng hoặc vùng Compute Engine của bạn. Tùy thuộc vào chế độ hoạt động mà bạn chọn sử dụng trong GKE, hãy chỉ định vùng hoặc vùng mặc định. Nếu bạn sử dụng chế độ Tiêu chuẩn, cụm của bạn là vùng (đối với hướng dẫn này), vì vậy hãy đặt vùng tính toán mặc định của bạn. Nếu bạn sử dụng chế độ Lái tự động, thì cụm của bạn là khu vực, vì vậy hãy đặt khu vực điện toán mặc định của bạn. Chọn một vùng hoặc khu vực gần nhất với kho lưu trữ Artifact Registry mà bạn đã tạo Standardcluster, chẳng hạn như chúng tôi-tây1-a: cấu hình gcloud đặt tính toán/vùng COMPUTE_ZONE Autopilotcluster, chẳng hạn như chúng tôi-tây1: cấu hình gcloud đặt tính toán/khu vực MÁY TÍNH_REGION - Tạo một cụm có tên xin chào-cụm: Cụm tiêu chuẩn: cụm vùng chứa gcloud tạo cụm chào Cụm lái tự động: cụm vùng chứa gcloud tạo-tự động chào cụm Mất vài phút để cụm GKE của bạn được tạo và kiểm tra tình trạng - Sau khi lệnh hoàn thành, hãy chạy lệnh sau để xem ba Nút của cụm: kubectl nhận các nút Đầu ra: TÊN TRẠNG THÁI VAI TRÒ TUỔI PHIÊN BẢN gke-hello-cluster-default-pool-229c0700-cbtd Sẵn sàng 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