Deploying a containerized web application  |  Kubernetes Engine  |  Google Cloud (2024)

Create a repository

In this tutorial, you store an image in Artifact Registry and deploy itfrom the registry. For this quickstart, you'll create a repository namedhello-repo.

  1. Set the PROJECT_ID environment variable to your Google Cloud project ID(PROJECT_ID). You'll use this environment variablewhen you build the container image and push it to your repository.

    export PROJECT_ID=PROJECT_ID
  2. Confirm that the PROJECT_ID environment variable has the correct value:

    echo $PROJECT_ID
  3. Set your project IDfor the Google Cloud CLI:

    gcloud config set project $PROJECT_ID

    Output:

    Updated property [core/project].
  4. Create the hello-repo repository with the following command:

    gcloud artifacts repositories create hello-repo \ --repository-format=docker \ --location=REGION \ --description="Docker repository"

    Replace REGION with the a region for therepository, such as us-west1. To see a list of available locations,run the command:

     gcloud artifacts locations list

Building the container image

In this tutorial, you deploy a sample webapplication called hello-app, a web server writtenin Go that responds to all requests with the messageHello, World! on port 8080.

GKE accepts Docker images as the application deployment format.Before deploying hello-app to GKE, you must packagethe hello-app source code as a Docker image.

To build a Docker image, you need source code and a Dockerfile.A Dockerfile contains instructions on how the image is built.

  1. Download the hello-app source code and Dockerfile by running the following commands:

    git clone https://github.com/GoogleCloudPlatform/kubernetes-engine-samplescd kubernetes-engine-samples/quickstarts/hello-app
  2. Build and tag the Docker image for hello-app:

    docker build -t REGION-docker.pkg.dev/${PROJECT_ID}/hello-repo/hello-app:v1 .

    This command instructs Docker to build the image using the Dockerfile inthe current directory, save it to your local environment, and tag it with aname, such as us-west1-docker.pkg.dev/my-project/hello-repo/hello-app:v1.The image is pushed to Artifact Registry in the next section.

    • The PROJECT_ID variable associates the container image with the hello-reporepository in your Google Cloud project.
    • The us-west1-docker.pkg.dev prefix refers to Artifact Registry,regional host for your repository.
  3. Run the docker images command to verify that the build was successful:

    docker images

    Output:

    REPOSITORY TAG IMAGE ID CREATED SIZEus-west1-docker.pkg.dev/my-project/hello-repo/hello-app v1 25cfadb1bf28 10 seconds ago 54 MB
  4. Add IAM policy bindings to your service account:

    gcloud artifacts repositories add-iam-policy-binding hello-repo \ --location=REGION \ --member=serviceAccount:PROJECT_NUMBER-compute@developer.gserviceaccount.com \ --role="roles/artifactregistry.reader"

    Replace PROJECT_NUMBER with theproject numberof your project.

Running your container locally (optional)

  1. Test your container image using your local Docker engine:

    docker run --rm -p 8080:8080 REGION-docker.pkg.dev/${PROJECT_ID}/hello-repo/hello-app:v1
  2. Click the Web Preview button Deploying a containerized web application | Kubernetes Engine | Google Cloud (1)and then select the 8080 port number. GKE opens thepreview URL on its proxy service in a new browser window.

Pushing the Docker image to Artifact Registry

You must upload the container image to a registry so that your GKEcluster can download and run the container image. In this tutorial, you willstore your container in Artifact Registry.

  1. Configure the Docker command-line tool to authenticate toArtifact Registry:

    gcloud auth configure-docker REGION-docker.pkg.dev
  2. Push the Docker image that you just built to the repository:

    docker push REGION-docker.pkg.dev/${PROJECT_ID}/hello-repo/hello-app:v1

Creating a GKE cluster

Now that the Docker image is stored in Artifact Registry, create a GKEclusterto run hello-app. A GKE cluster consists of a pool of Compute Engine VM instancesrunning Kubernetes, the open source cluster orchestrationsystem that powers GKE.

Cloud Shell

  1. Set your Compute Engine region:

     gcloud config set compute/region REGION

    For Standard zonal clusters, set a Compute Engine zonenearest to the Artifact Registry repository.

  2. Create a cluster named hello-cluster:

     gcloud container clusters create-auto hello-cluster

    It takes a few minutes for your GKE cluster to becreated and health-checked. To run this tutorial on a GKEStandard cluster, use thegcloud container clusters createcommand instead.

Console

  1. Go to the Google Kubernetes Engine page in the Google Cloud console.

    Go to Google Kubernetes Engine

  2. Click add_box Create.

  3. For GKE Autopilot, clickConfigure.

  4. In the Name field, enter the name hello-cluster.

  5. Select a Compute Engine regionfrom the Region drop-down list, such as us-west1.

  6. Click Create.

  7. Wait for the cluster to be created. When the cluster is ready, acheckmark 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 scalableunits 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 acrossyour 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 yourcluster. This Deployment has replicas (Pods). One Deployment Pod contains onlyone container: the hello-app Docker image.You also create a HorizontalPodAutoscaler resource that scales the numberof Pods from 3 to a number between 1 and 5, based on CPU load.

Cloud Shell

  1. Ensure that you are connected to your GKE cluster.

    gcloud container clusters get-credentials hello-cluster --region REGION
  2. Create a Kubernetes Deployment for your hello-app Docker image.

    kubectl create deployment hello-app --image=REGION-docker.pkg.dev/${PROJECT_ID}/hello-repo/hello-app:v1
  3. Set the baseline number of Deployment replicas to 3.

    kubectl scale deployment hello-app --replicas=3
  4. Create a HorizontalPodAutoscaler resource for your Deployment.

    kubectl autoscale deployment hello-app --cpu-percent=80 --min=1 --max=5
  5. To see the Pods created, run the following command:

    kubectl get pods

    Output:

    NAME READY STATUS RESTARTS AGEhello-app-784d7569bc-hgmpx 1/1 Running 0 90shello-app-784d7569bc-jfkz5 1/1 Running 0 90shello-app-784d7569bc-mnrrl 1/1 Running 0 95s

Console

  1. Go to the Workloads page in the Google Cloud console.

    Visit Workloads

  2. Click add_box Deploy.

  3. In the Specify container section, select Existing container image.

  4. In the Image path field, click Select.

  5. In the Select container image pane, select the hello-app image youpushed to Artifact Registry and click Select.

  6. In the Container section, click Done, then click Continue.

  7. In the Configuration section, under Labels, enter app for Key and hello-app for Value.

  8. Under Configuration YAML, click View YAML. This opens a YAMLconfiguration file representing the two Kubernetes API resources about tobe deployed into your cluster: one Deployment, and oneHorizontalPodAutoscaler for that Deployment.

  9. Click Close, then click Deploy.

  10. When the Deployment Pods are ready, the Deployment details page opens.

  11. 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 stoppingbased on scaling needs. And when a Pod crashes due to an error,GKE automatically redeploys that Pod, assigning a new Pod IPaddress each time.

What this means is that for any Deployment, the set of IP addressescorresponding to the active set of Pods is dynamic. We need a way to 1) groupPods together into one static hostname, and 2) expose a group of Pods outsidethe cluster, to the internet.

Kubernetes Services solve for both of these problems.Services group Podsinto one static IP address, reachable from any Pod inside the cluster.GKE also assigns a DNS hostnameto 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 oftype 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 aService of type LoadBalancer.

Cloud Shell

  1. Use the kubectl expose command to generate a Kubernetes Service for thehello-app deployment:

    kubectl expose deployment hello-app --name=hello-app-service --type=LoadBalancer --port 80 --target-port 8080

    Here, the --port flag specifies the port number configured on the Load Balancer, andthe --target-port flag specifies the port number that the hello-appcontainer is listening on.

  2. Run the following command to get the Service details for hello-app-service:

    kubectl get service

    Output:

    NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGEhello-app-service 10.3.251.122 203.0.113.0 80:30877/TCP 10s
  3. Copy the EXTERNAL_IP address to the clipboard (for instance: 203.0.113.0).

Console

  1. Go to the Workloads page in the Google Cloud console.

    Go to Workloads

  2. Click hello-app.

  3. From the Deployment details page, click list Actions > Expose.

  4. In the Expose dialog, set the Target port to 8080.This is the port the hello-app container listens on.

  5. From the Service type drop-down list, select Load balancer.

  6. Click Expose to create a Kubernetes Service for hello-app.

  7. When the Load Balancer is ready, the Service details page opens.

  8. Scroll down to the External endpoints field, 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 copiedto the clipboard. A Hello, World! message appears, along with a Hostnamefield. The Hostname corresponds to one of the three hello-app Pods serving yourHTTP 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 deployinga new Docker image to your GKE cluster.

GKE's rolling update featurelets you update your Deployments without downtime. During a rolling update, your GKE clusterincrementally 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.

  1. Return to Cloud Shell, where you have cloned the hello app source code and Dockerfile.Update the function hello() in the main.go file to report the new version 2.0.0.

  2. Build and tag a new hello-app Docker image.

    docker build -t REGION-docker.pkg.dev/${PROJECT_ID}/hello-repo/hello-app:v2 .
  3. Push the image to Artifact Registry.

    docker push REGION-docker.pkg.dev/${PROJECT_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

  1. Apply a rolling update to the existing hello-app Deployment withan image update using thekubectl set image command:

    kubectl set image deployment/hello-app hello-app=REGION-docker.pkg.dev/${PROJECT_ID}/hello-repo/hello-app:v2
  2. Watch the running Pods running the v1 image stop, and new Pods running thev2 image start.

    watch kubectl get pods

    Output:

    NAME READY STATUS RESTARTS AGEhello-app-89dc45f48-5bzqp 1/1 Running 0 2m42shello-app-89dc45f48-scm66 1/1 Running 0 2m40s
  3. In a separate tab, navigate again to the hello-app-service External IP. You should now seethe Version set to 2.0.0.

Console

  1. Go to the Workloads page in the Google Cloud console.

    Go to Workloads

  2. Click hello-app.

  3. On the Deployment details page, click listActions > Rolling update.

  4. In the Rolling update dialog, set the Image of hello-app field toREGION-docker.pkg.dev/PROJECT_ID/hello-repo/hello-app:v2.

  5. Click Update.

  6. On the Deployment details page, inspect the Active Revisionssection. You should now see two Revisions, 1 and 2. Revision 1 correspondsto the initial Deployment you created earlier. Revision 2 is the rollingupdate you just started.

  7. After a few moments, refresh the page. Under Managed pods, all of thereplicas of hello-app now correspond to Revision 2.

  8. In a separate tab, navigate again to the Service IP address you copied.The Version should be 2.0.0.

Deploying a containerized web application  |  Kubernetes Engine  |  Google Cloud (2024)
Top Articles
Latest Posts
Article information

Author: Merrill Bechtelar CPA

Last Updated:

Views: 6720

Rating: 5 / 5 (50 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Merrill Bechtelar CPA

Birthday: 1996-05-19

Address: Apt. 114 873 White Lodge, Libbyfurt, CA 93006

Phone: +5983010455207

Job: Legacy Representative

Hobby: Blacksmithing, Urban exploration, Sudoku, Slacklining, Creative writing, Community, Letterboxing

Introduction: My name is Merrill Bechtelar CPA, I am a clean, agreeable, glorious, magnificent, witty, enchanting, comfortable person who loves writing and wants to share my knowledge and understanding with you.