Running a Containerized App on Google Kubernetes Engine - GSP015

David NguyenDavid Nguyen
10 min read

Overview

Google Kubernetes Engine makes it easy to run Docker containers in the cloud. Google Kubernetes Engine uses Kubernetes, an open source container scheduler, to ensure that your cluster is running exactly the way you want it to at all times.

In this lab you will learn how to launch a container and how to launch replicas of that container on Google Kubernetes Engine.

Setup and requirements

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources are made available to you.

This hands-on lab lets you do the lab activities in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).

Note: Use an Incognito (recommended) or private browser window to run this lab. This prevents conflicts between your personal account and the student account, which may cause extra charges incurred to your personal account.

  • Time to complete the lab—remember, once you start, you cannot pause a lab.

Note: Use only the student account for this lab. If you use a different Google Cloud account, you may incur charges to that account.

How to start your lab and sign in to the Google Cloud console

  1. Click the Start Lab button. If you need to pay for the lab, a dialog opens for you to select your payment method. On the left is the Lab Details pane with the following:

    • The Open Google Cloud console button

    • Time remaining

    • The temporary credentials that you must use for this lab

    • Other information, if needed, to step through this lab

  2. Click Open Google Cloud console (or right-click and select Open Link in Incognito Window if you are running the Chrome browser).

    The lab spins up resources, and then opens another tab that shows the Sign in page.

    Tip: Arrange the tabs in separate windows, side-by-side.

    Note: If you see the Choose an account dialog, click Use Another Account.

  3. If necessary, copy the Username below and paste it into the Sign in dialog.

     student-03-dc0dbd6b08e0@qwiklabs.net
    

    You can also find the Username in the Lab Details pane.

  4. Click Next.

  5. Copy the Password below and paste it into the Welcome dialog.

     Vs7YzfeT2sT8
    

    You can also find the Password in the Lab Details pane.

  6. Click Next.

    Important: You must use the credentials the lab provides you. Do not use your Google Cloud account credentials.

    Note: Using your own Google Cloud account for this lab may incur extra charges.

  7. Click through the subsequent pages:

    • Accept the terms and conditions.

    • Do not add recovery options or two-factor authentication (because this is a temporary account).

    • Do not sign up for free trials.

After a few moments, the Google Cloud console opens in this tab.

Note: To access Google Cloud products and services, click the Navigation menu or type the service or product name in the Search field.

Navigation menu icon and Search field

Activate Cloud Shell

Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.

  1. Click Activate Cloud Shell at the top of the Google Cloud console.

  2. Click through the following windows:

    • Continue through the Cloud Shell information window.

    • Authorize Cloud Shell to use your credentials to make Google Cloud API calls.

When you are connected, you are already authenticated, and the project is set to your Project_ID, qwiklabs-gcp-02-50135e6f15c2. The output contains a line that declares the Project_ID for this session:

Your Cloud Platform project in this session is set to qwiklabs-gcp-02-50135e6f15c2

gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.

  1. (Optional) You can list the active account name with this command:
gcloud auth list
  1. Click Authorize.

Output:

ACTIVE: *
ACCOUNT: student-03-dc0dbd6b08e0@qwiklabs.net

To set the active account, run:
    $ gcloud config set account `ACCOUNT`
  1. (Optional) You can list the project ID with this command:
gcloud config list project

Output:

[core]
project = qwiklabs-gcp-02-50135e6f15c2

Note: For full documentation of gcloud, in Google Cloud, refer to the gcloud CLI overview guide.

Task 1. Creating a cluster

In this section you'll create a Google Kubernetes Engine cluster.

Set compute zone

Cloud Shell is a browser based terminal to a virtual machine that has the Google Cloud tools installed on it and some additional tools (like editors and compilers) that are handy when you are developing or debugging your cloud application.

You'll be using the gcloud command to create the cluster. First, set the compute zone so that the virtual machines in your cluster are created in the correct region. Do this using gcloud config set compute/zone.

  • Enter the following in Cloud Shell:
gcloud config set compute/zone us-east4-a

Understanding Regions and Zones

Certain Compute Engine resources live in regions or zones. A region is a specific geographical location where you can run your resources. Each region has one or more zones. For example, the us-central1 region denotes a region in the Central United States that has zones us-central1-a, us-central1-b, us-central1-c, and us-central1-f.

RegionsZones
Western USus-west1-a, us-west1-b
Central USus-central1-a, us-central1-b, us-central1-d, us-central1-f
Eastern USus-east1-b, us-east1-c, us-east1-d
Western Europeeurope-west1-b, europe-west1-c, europe-west1-d
Eastern Asiaasia-east1-a, asia-east1-b, asia-east1-c

Resources that live in a zone are referred to as zonal resources. Virtual machine Instances and persistent disks live in a zone. To attach a persistent disk to a virtual machine instance, both resources must be in the same zone. Similarly, if you want to assign a static IP address to an instance, the instance must be in the same region as the static IP.

Learn more about regions and zones and see a complete list in the Compute Engine page, Regions and zones documentation).

Create a new cluster

  • Create a new container cluster with the gcloud command like this:
gcloud container clusters create hello-world

This command creates a new cluster called hello-world with three nodes (VMs). You can configure this command with additional flags to change the number of nodes, the default permissions, and other variables. Refer to the gcloud container clusters create reference for more details.

Note: If you get an error when running gcloud container clusters create ensure that you have enabled both the Google Kubernetes Engine and Compute Engine APIs.

Launching the cluster may take a few minutes. Once it is up you should see output in Cloud Shell that looks like this:

NAME         LOCATION       MASTER_VERSION  MASTER_IP      MACHINE_TYPE   NODE_VERSION  NUM_NODES  STATUS
hello-world  us-east4-a  1.12.7-gke.10     35.239.64.154  e2-medium  1.12.7-gke.10   3          RUNNING

Test completed task

Click Check my progress to verify your performed task. If you have completed the task successfully you will be granted with an assessment score.

Assessment Completed!

Create a Kubernetes Cluster.

Assessment Completed!

Task 2. Building and publishing the Hello World app

Next, build and publish a container that contains your code. You will use Docker to build the container, and Google Artifact Registry to securely publish it.

Set your project ID

You will use Project ID in many of the commands in this lab. The Project ID is conveniently stored in an environment variable in Cloud Shell. You can see it here:

echo $DEVSHELL_PROJECT_ID

Task 3. Get the sample code

  1. Run the following to clone the samples:
git clone https://github.com/GoogleCloudPlatform/kubernetes-engine-samples
  1. Change directories:
cd kubernetes-engine-samples/quickstarts/hello-app

Build the container

Docker containers are built using a Dockerfile. The sample code provides a basic Dockerfile that we can use.

cat Dockerfile

Here is the contents of the file:

...
FROM golang:1.19.2 as builder
WORKDIR /app
RUN go mod init hello-app
COPY *.go ./
RUN CGO_ENABLED=0 GOOS=linux go build -o /hello-app

FROM gcr.io/distroless/base-debian11
WORKDIR /
COPY --from=builder /hello-app /hello-app
ENV PORT 8080
USER nonroot:nonroot
CMD ["/hello-app"]
  • To build the container, run the following command:
docker build -t gcr.io/$DEVSHELL_PROJECT_ID/hello-app:1.0 .

This will build a Docker container image stored locally.

Publish the container

In order for Kubernetes to access your image, you need to store it in a container registry.

  • Run the following command to publish your container image:
gcloud docker -- push gcr.io/$DEVSHELL_PROJECT_ID/hello-app:1.0

Task 4. Deploying the Hello World app

Now that we have a cluster running and our application built, it is time to deploy it.

Create your deployment

A deployment is a core component of Kubernetes that makes sure your application is always running. A deployment schedules and manages a set of pods on the cluster. A pod is one or more containers that "travel together". That might mean they are administered together or they have the same network requirements. For this lab there is only one container in your pod.

Typically you would create a yaml file with the configuration for the deployment. For this lab will skip this step and instead directly create the deployment on the command line.

  1. Create the pod using kubectl:
kubectl create deployment hello-app --image=gcr.io/$DEVSHELL_PROJECT_ID/hello-app:1.0

Note: You can safely ignore any command deprecation warnings.

This command starts up one copy of the Docker image on one of the nodes in the cluster.

Test completed task

Click Check my progress to verify your performed task. If you have completed the task successfully you will be granted with an assessment score.

Build and Deploy Hello World App (hello-app)

  1. Run the following to see the deployment you created using kubectl:
kubectl get deployments

You should get back a result that looks something like:

NAME          READY   UP-TO-DATE   AVAILABLE   AGE
hello-app    1/1     1            1           30s
  1. You can see the pod running using kubectl as well:
kubectl get pods

You should get back a result that looks something like:

NAME                            READY     STATUS    RESTARTS   AGE
hello-app-3375482827-7hs3q     1/1       Running   0          1m

Allow external traffic

By default, a pod is only accessible to other machines inside the cluster. In order to use the app container that was created, it needs to be exposed as a service.

Typically, you would create a yaml file with the configuration for the service. For this lab will skip this step and instead directly create the deployment on the command line.

  1. Run the following to expose the deployment with the kubectl expose command:
kubectl expose deployment hello-app --name=hello-app --type=LoadBalancer --port=80 --target-port=8080

kubectl expose creates a service, the forwarding rules for the load balancer, and the firewall rules that allow external traffic to be sent to the pod. The --type=LoadBalancer flag creates a Google Cloud Network Load Balancer that will accept external traffic.

  1. To get the IP address for your service, run the following command:
kubectl get svc hello-app

You should get back a result that looks something like:

NAME       TYPE         CLUSTER-IP    EXTERNAL-IP       PORT(S)   AGE
hello-app LoadBalancer 10.3.247.85   104.198.151.208   80/TCP    8m

Note: It may take a minute or so for the External-IP to populate. If you see <pending> for the External-IP, wait 30 seconds and try again.

Test completed task

Click Check my progress to verify your performed task. If you have completed the task successfully you will be granted with an assessment score.

Allow external traffic to hello-app deployment.

Verify the deployment

Open a new browser window or tab and navigate to the external IP address from the previous step. You should see the sample code up and running!

The web page displaying the following text: Hello Kubernetes!

Task 5. Test your understanding

Below are multiple-choice questions to reinforce your understanding of this lab's concepts. Answer them to the best of your abilities.

docker push publish the container image in Google Cloud to ____.

  • Source Repository

  • Container Registry

  • Cloud Storage

Kubernetes is an open-source container-orchestration system for automating deployment, scaling and management of containerized applications.

  • True

  • False

In Kubernetes environment, kubectl expose creates a ____, the forwarding rules for the load balancer, and the firewall rules that allow external traffic to be sent to the pod.

  • Cluster

  • Node

  • Service

  • Pod


Solution of Lab

curl -LO raw.githubusercontent.com/Techcps/Google-Cloud-Skills-Boost/master/Running%20a%20Containerized%20App%20on%20Google%20Kubernetes%20Engine/techcps015.sh
sudo chmod +x techcps015.sh
./techcps015.sh
0
Subscribe to my newsletter

Read articles from David Nguyen directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

David Nguyen
David Nguyen

A passionate full-stack developer from @ePlus.DEV