Este tutorial le muestra cómo empaquetar una aplicación web en una imagen de contenedor de Docker y ejecutar esa imagen de contenedor en un clúster de Google Kubernetes Engine (GKE). Luego, implementa la aplicación web como un conjunto de réplicas con equilibrio de carga que puede adaptarse a las necesidades de sus usuarios. ## Objetivos - Empaquete una aplicación web de muestra en una imagen de Docker - Cargue la imagen de Docker en Artifact Registry - Crear un clúster de GKE - Implementar la aplicación de muestra en el clúster - Administrar el escalado automático para la implementación. - Exponer la aplicación de muestra a Internet - Implementar una nueva versión de la aplicación de muestra ## Costos Este instructivo usa los siguientes componentes facturables de Google Cloud: Para generar una estimación de costos basada en su uso proyectado, usa la calculadora de precios Cuando termine este tutorial, puede evitar la facturación continua eliminando los recursos que creó. Para obtener más información, consulte Limpiar ## Antes de comenzar Siga los siguientes pasos para habilitar la API de Kubernetes Engine: - Inicie sesión en su cuenta de Google Cloud. Si es nuevo en Google Cloud, cree una cuenta para evaluar el rendimiento de nuestros productos en escenarios del mundo real. Los nuevos clientes también obtienen $300 en créditos gratuitos para ejecutar, probar e implementar cargas de trabajo - En la consola de Google Cloud, en la página de selección de proyectos, seleccione o cree un proyecto de Google Cloud - Asegúrate de que la facturación esté habilitada para tu proyecto de Cloud. Más información sobre cómo verificar si la facturación está habilitada en un proyecto - Habilite las API de Artifact Registry y Google Kubernetes Engine - En la consola de Google Cloud, en la página de selección de proyectos, seleccione o cree un proyecto de Google Cloud - Asegúrate de que la facturación esté habilitada para tu proyecto de Cloud. Más información sobre cómo verificar si la facturación está habilitada en un proyecto - Habilite las API de Artifact Registry y Google Kubernetes Engine Opción A: Usar Cloud Shell Puede seguir este tutorial usando Cloud Shell, que viene preinstalado con el gnube, estibador, y herramientas de línea de comandos de kubectl utilizadas en este tutorial. Si usa Cloud Shell, no necesita instalar estos herramientas de línea de comandos en su estación de trabajo Para usar CloudShell: - Ir a la consola de Google Cloud Haga clic en el Activar CloudShell botón en la parte superior de la ventana de la consola de Google Cloud Se abre una sesión de Cloud Shell dentro de un nuevo marco en la parte inferior de la consola de Google Cloud y muestra un mensaje de línea de comandos. Opción B: Usar herramientas de línea de comandos localmente Si prefiere seguir este tutorial en su estación de trabajo, siga estos pasos para instalar las herramientas necesarias Instalar la CLI de Google Cloud Mediante la CLI de gcloud, instale la herramienta de línea de comandos de Kubernetes kubectlis solía comunicarse con Kubernetes, que es el sistema de orquestación de clústeres de los clústeres de GKE: los componentes de gcloud instalan kubectl Instale Docker Community Edition (CE) en su estación de trabajo. Usas esto para construir una imagen de contenedor para la aplicación. Instale la herramienta de control de fuente de Git para obtener la aplicación de muestra de GitHub ## Crear un repositorio En este tutorial, almacena una imagen en Artifact Registry y la implementa del registro Artifact Registry es el registro de contenedor recomendado en Nube de Google. Para este inicio rápido, creará un repositorio llamado hola-repo Selecciona el PROJECT_IDvariable de entorno a su ID de proyecto de Google Cloud ( ). Usarás esta variable de entorno cuando construyas la imagen del contenedor y la envíes a tu repositorio. PROJECTO ID exportar PROYECTO_ID= PROJECTO ID Confirme que el La variable PROJECT_IDenvironment tiene el valor correcto: echo $PROJECT_ID Configure su ID de proyecto para la CLI de Google Cloud: proyecto de conjunto de configuración de gcloud $PROJECT_ID Producción: Propiedad actualizada [núcleo/proyecto] Crear el hola-repositorio con el siguiente comando: Los repositorios de artefactos de gcloud crean hello-repo \ --repository-format=docker \ --location= REGIÓN\ --description="Repositorio Docker"Reemplazar con la región a para el repositorio, como REGIÓN us-west1. Para ver una lista de ubicaciones disponibles, ejecute el comando: lista de ubicaciones de artefactos de gcloud ## Construyendo la imagen del contenedor En este tutorial, implementa una web de muestra aplicación llamada hello-app, un servidor web escrito en Go que responde a todas las solicitudes con el mensaje ¡Hola Mundo! en el puerto 8080 GKE acepta imágenes de Docker como formato de implementación de la aplicación Antes de implementar hello-app a GKE, debes empaquetar la código fuente de hello-app como una imagen de Docker Para crear una imagen de Docker, necesita el código fuente y un Dockerfile. Un Dockerfile contiene instrucciones sobre cómo se crea la imagen. Descargar el hello-appsource code y Dockerfile ejecutando los siguientes comandos: clon de git httpsgithub.com/GoogleCloudPlatform/kubernetes-engine-samples cd kubernetes-engine-samples/hello-app Cree y etiquete la imagen de Docker para hola-aplicacion: ventana acoplable construir -t REGION-docker.pkg.devPROJECT_ID}/hello-repo/hello-app:v1 Este comando le indica a Docker que construya la imagen usando el Dockerfile en el directorio actual, guárdelo en su entorno local y etiquételo con un nombre, como us-west1-docker.pkg.dev/my-project/hello-repo/hello-app:v1. La imagen se envía a Artifact Registry en la siguiente sección - Él La variable PROJECT_ID asocia la imagen del contenedor con el hello-repository en tu proyecto de Google Cloud - Él us-west1-docker.pkg.devprefix hace referencia a Artifact Registry, host regional para su repositorio - Él ejecutar el docker imagescommand para verificar que la compilación fue exitosa: Imágenes de docker Producción: ID DE LA IMAGEN DE LA ETIQUETA DEL REPOSITOR TAMAÑO CREADO us-west1-docker.pkg.dev/my-project/hello-repo/hello-app v1 25cfadb1bf28 Hace 10 segundos 54 MB ## Ejecutar su contenedor localmente (opcional) Pruebe la imagen de su contenedor usando su motor Docker local: ventana acoplable ejecutar --rm -p 8080:8080 REGION-docker.pkg.devPROJECT_ID}/hello-repo/hello-app:v1 Si usa Cloud Shell, haga clic en el Botón Vista previa web y luego seleccione el 8080número de puerto. GKE abre la URL de vista previa en su servicio de proxy en una nueva ventana del navegador De lo contrario, abra una nueva ventana de terminal (o una pestaña de Cloud Shell) y ejecute el siguiente comando para verificar que el contenedor funcione y responda a las solicitudes con "Hello, World rizo httplocalhost:8080 Una vez que haya visto una respuesta exitosa, puede bajar el contenedor presionando Ctrl+Cen la pestaña donde se encuentra el El comando docker run se está ejecutando ## Empujando la imagen de Docker a Artifact Registry Debe cargar la imagen del contenedor en un registro para que su clúster de GKE pueda descargar y ejecutar la imagen del contenedor. En este tutorial, almacenará su contenedor en Artifact Registry Configure la herramienta de línea de comandos de Docker para autenticarse en Artifact Registry: configuración de la ventana acoplable de autenticación de gcloud REGION-docker.pkg.dev Empuje la imagen de Docker que acaba de crear al repositorio: empuje de la ventana acoplable REGION-docker.pkg.devPROJECT_ID}/hello-repo/hello-app:v1 ## Crear un clúster de GKE Ahora que la imagen de Docker está almacenada en Artifact Registry, cree un GKE grupo correr hola-aplicacion. Un clúster de GKE consta de un grupo de instancias de VM de Compute Engine ejecutar Kubernetes, la orquestación de clústeres de código abierto sistema que alimenta a GKE Concha de nube Establece tu zona o región de Compute Engine. Según el modo de operación que elijas usar en GKE, especifica una zona o región predeterminada. Si usa el modo Estándar, su clúster es zonal (para este tutorial), así que configure su zona de cómputo predeterminada. Si usa el modo de piloto automático, su clúster es regional, así que configure su región de cómputo predeterminada. Elija una zona o región que esté más cerca del repositorio de Artifact Registry que creó Grupo estándar, como us-west1-a: conjunto de configuración de gcloud cómputo/zona Clúster de piloto automático COMPUTE_ZONE, como us-west1: conjunto de configuración de gcloud cómputo/región COMPUTE_REGION - Crear un clúster llamado hola-cluster: Clúster estándar: los clústeres de contenedores de gcloud crean un clúster de saludo Clúster de piloto automático: clústeres de contenedores de gcloud create-auto hello-cluster Se tarda unos minutos en crear y comprobar el estado de su clúster de GKE. - Una vez que se complete el comando, ejecute el siguiente comando para ver los tres nodos del clúster: kubectl obtener nodos Producción: NOMBRE ESTADO FUNCIONES EDAD VERSIÓN gke-hello-cluster-default-pool-229c0700-cbtd Listo 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