Questo tutorial mostra come creare un pacchetto di un'applicazione web in un'immagine di container Docker ed eseguire tale immagine di container su un cluster Google Kubernetes Engine (GKE). Quindi, distribuisci l'applicazione Web come set di repliche con bilanciamento del carico in grado di adattarsi alle esigenze degli utenti ## Obiettivi - Crea un pacchetto di un'applicazione Web di esempio in un'immagine Docker - Carica l'immagine Docker su Artifact Registry - Crea un cluster GKE - Distribuire l'app di esempio nel cluster - Gestire la scalabilità automatica per la distribuzione - Esponi l'app di esempio a Internet - Distribuire una nuova versione dell'app di esempio ## Costi Questo tutorial utilizza i seguenti componenti fatturabili di Google Cloud: Per generare una stima dei costi basata sull'utilizzo previsto, utilizzare il calcolatore dei prezzi Al termine di questo tutorial, puoi evitare la fatturazione continua eliminando le risorse che hai creato. Per ulteriori informazioni, vedere Pulizia ## Prima di iniziareEsegui i seguenti passaggi per abilitare l'API Kubernetes Engine: - Accedi al tuo account Google Cloud. Se non conosci Google Cloud, crea un account per valutare le prestazioni dei nostri prodotti in scenari reali. I nuovi clienti ricevono anche $ 300 in crediti gratuiti per eseguire, testare e distribuire carichi di lavoro - Nella console di Google Cloud, nella pagina di selezione del progetto, seleziona o crea un progetto Google Cloud - Assicurati che la fatturazione sia abilitata per il tuo progetto Cloud. Scopri come verificare se la fatturazione è abilitata su un progetto - Abilita le API Artifact Registry e Google Kubernetes Engine - Nella console di Google Cloud, nella pagina di selezione del progetto, seleziona o crea un progetto Google Cloud - Assicurati che la fatturazione sia abilitata per il tuo progetto Cloud. Scopri come verificare se la fatturazione è abilitata su un progetto - Abilita le API Artifact Registry e Google Kubernetes Engine Opzione A: utilizzare Cloud Shell Puoi seguire questo tutorial utilizzando Cloud Shell, che viene fornito preinstallato con il cloud, docker, e strumenti da riga di comando kubectl utilizzati in questo tutorial. Se utilizzi Cloud Shell, non è necessario installarli strumenti della riga di comando sulla tua workstation Per utilizzare Cloud Shell: - Vai alla console di Google Cloud Clicca il Attiva Cloud Shell pulsante nella parte superiore della finestra della console di Google Cloud Una sessione di Cloud Shell si apre all'interno di un nuovo frame nella parte inferiore della console di Google Cloud e visualizza un prompt della riga di comando Opzione B: utilizzare gli strumenti della riga di comando in locale Se preferisci seguire questo tutorial sulla tua workstation, segui questi passaggi per installare gli strumenti necessari Installa l'interfaccia a riga di comando di Google Cloud Utilizzando l'interfaccia a riga di comando di gcloud, installa lo strumento da riga di comando Kubernetes kubectlis era utilizzato per comunicare con Kubernetes, che è il sistema di orchestrazione dei cluster GKE: I componenti gcloud installano kubectl Installa Docker Community Edition (CE) sulla tua workstation. Puoi usarlo per creare un'immagine contenitore per l'applicazione Installa lo strumento di controllo del codice sorgente Git per recuperare l'applicazione di esempio da GitHub ## Crea un archivio In questo tutorial, memorizzi un'immagine in Artifact Registry e la distribuisci dal registro. Artifact Registry è il registro contenitori consigliato Google Cloud. Per questo avvio rapido, creerai un repository denominato ciao-repo Impostare il PROJECT_IDvariabile di ambiente per il tuo ID progetto Google Cloud ( ). Utilizzerai questa variabile di ambiente quando crei l'immagine del contenitore e la invii al tuo repository ID_PROGETTO esporta PROJECT_ID= ID_PROGETTO Conferma che il La variabile PROJECT_IDenvironment ha il valore corretto: echo $PROJECT_ID Imposta il tuo ID progetto per l'interfaccia a riga di comando di Google Cloud: progetto set di configurazione gcloud $PROJECT_ID Produzione: Proprietà aggiornata [core/progetto] Crea il hello-reporepository con il seguente comando: i repository di artefatti gcloud creano hello-repo \ --repository-format=docker \ --location= REGION\ --description="Repository Docker"Sostituire con una regione per il repository, ad esempio REGIONE noi-ovest1. Per visualizzare un elenco di posizioni disponibili, eseguire il comando: elenco delle posizioni degli artefatti gcloud ## Costruire l'immagine del contenitore In questa esercitazione si distribuisce un file Web di esempio applicazione chiamata ciao-app, un server web scritto in Go che risponde a tutte le richieste con il messaggio Ciao mondo! sulla porta 8080 GKE accetta le immagini Docker come formato di distribuzione dell'applicazione Prima della distribuzione hello-app a GKE, devi creare un pacchetto il codice sorgente hello-app come immagine Docker Per creare un'immagine Docker, sono necessari il codice sorgente e un Dockerfile. Un Dockerfile contiene le istruzioni su come viene creata l'immagine Scarica il hello-appsource code e Dockerfile eseguendo i seguenti comandi: clone git httpsgithub.com/GoogleCloudPlatform/kubernetes-engine-samples cd kubernetes-engine-samples/hello-app Crea e contrassegna l'immagine Docker per ciao-app: finestra mobile costruire -t REGION-docker.pkg.devPROJECT_ID}/ciao-repo/ciao-app:v1 Questo comando indica a Docker di creare l'immagine utilizzando il file Dockerfile nella directory corrente, salvalo nel tuo ambiente locale e contrassegnalo con un nome, ad esempio us-west1-docker.pkg.dev/my-project/hello-repo/hello-app:v1. L'immagine viene inviata a Artifact Registry nella sezione successiva - Il La variabile PROJECT_ID associa l'immagine del contenitore al file hello-repository nel tuo progetto Google Cloud - Il us-west1-docker.pkg.devprefix fa riferimento a Artifact Registry, host regionale per il tuo repository - Il Corri il comando docker images per verificare che la compilazione sia andata a buon fine: immagini di docker Produzione: TAG DEL REPOSITORY ID IMMAGINE CREATO DIMENSIONE us-west1-docker.pkg.dev/my-project/hello-repo/hello-app v1 25cfadb1bf28 10 secondi fa 54 MB ## Esecuzione del tuo contenitore in locale (facoltativo) Testa l'immagine del tuo contenitore utilizzando il tuo motore Docker locale: finestra mobile eseguire --rm -p 8080:8080 REGION-docker.pkg.devPROJECT_ID}/ciao-repo/ciao-app:v1 Se utilizzi Cloud Shell, fai clic su Pulsante Anteprima Web e quindi selezionare il numero di porta 8080. GKE apre l'URL di anteprima sul proprio servizio proxy in una nuova finestra del browser In caso contrario, apri una nuova finestra del terminale (o una scheda Cloud Shell) ed esegui il seguente comando per verificare che il container funzioni e risponda alle richieste con "Hello, World curl httplocalhost:8080 Dopo aver visto una risposta positiva, puoi scaricare il contenitore premendo Ctrl+Cnella scheda in cui il file docker runcommand è in esecuzione ## Inserimento dell'immagine Docker in Artifact Registry Devi caricare l'immagine del container in un registro in modo che il tuo cluster GKE possa scaricare ed eseguire l'immagine del container. In questo tutorial, archivierai il tuo contenitore in Artifact Registry Configura lo strumento da riga di comando Docker per l'autenticazione in Artifact Registry: finestra mobile di configurazione dell'autenticazione gcloud REGION-docker.pkg.dev Invia l'immagine Docker che hai appena creato al repository: spinta del docker REGION-docker.pkg.devPROJECT_ID}/ciao-repo/ciao-app:v1 ## Creazione di un cluster GKE Ora che l'immagine Docker è archiviata in Artifact Registry, crea un GKE grappolo correre ciao-app. Un cluster GKE è costituito da un pool di istanze VM di Compute Engine eseguire Kubernetes, l'orchestrazione di cluster open source sistema che alimenta GKE Guscio Nuvoloso Imposta la zona o l'area geografica di Compute Engine. A seconda della modalità operativa che scegli di utilizzare in GKE, specifica una zona o un'area geografica predefinita. Se utilizzi la modalità Standard, il tuo cluster è di zona (per questo tutorial), quindi imposta la tua zona di calcolo predefinita. Se usi la modalità Autopilot, il tuo cluster è regionale, quindi imposta la tua area di calcolo predefinita. Scegli una zona o regione più vicina al repository Artifact Registry che hai creato Cluster standard, ad esempio noi-ovest1-a: set di configurazione gcloud compute/zone COMPUTE_ZONE Autopilot cluster, ad esempio noi-ovest1: set di configurazione gcloud calcolo/regione COMPUTE_REGION - Crea un cluster denominato ciao cluster: Grappolo standard: i cluster di contenitori gcloud creano hello-cluster Gruppo pilota automatico: cluster di contenitori gcloud create-auto hello-cluster Sono necessari alcuni minuti per la creazione e il controllo dello stato del tuo cluster GKE - Al termine del comando, esegui il comando seguente per visualizzare i tre nodi del cluster: kubectl ottiene i nodi Produzione: NOME STATO RUOLI ETÀ VERSIONE gke-hello-cluster-default-pool-229c0700-cbtd Pronto 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