arrow_back

Migrating to GKE Containers

Join Sign in

Migrating to GKE Containers

1 hour 15 minutes 5 Credits

GKE-Engine.png

GSP475

Google Cloud self-paced labs logo

Containers are quickly becoming an industry standard for deployment of software applications. The business and technological advantages of containerizing workloads are driving many teams towards moving their applications to containers. This lab provides a basic walkthrough of migrating a stateless application from running on a VM to running on Kubernetes Engine (GKE). It demonstrates the lifecycle of an application transitioning from a typical VM/OS-based deployment to a specialized os for containers to a platform for containers better known as GKE.

Overview

There are numerous advantages to using containers to deploy applications. Among these are:

  1. Isolated - Applications have their own libraries; no conflicts will arise from different libraries in other applications.

  2. Limited (limits on CPU/memory) - Applications may not hog resources from other applications.

  3. Portable - The container contains everything it needs and is not tied to an OS or Cloud provider.

  4. Lightweight - The kernel is shared, making it much smaller and faster than a full OS image.

What you'll learn

This project demonstrates migrating a simple Python application named Prime-flask to:

  1. A virtual machine (Debian VM) where Prime-flask is deployed as the only application, much like a traditional application is run in an on-premises datacenter

  2. A containerized version of Prime-flask is deployed on Container-Optimized OS (COS)

  3. A Kubernetes deployment where Prime-flask is exposed via a load balancer and deployed in Kubernetes Engine

After the deployment you'll run a load test against the final deployment and scale it to accommodate the load.

If during the lab you get an error, it probably makes sense to re-execute the failing script. Occasionally there are network connectivity issues, and retrying will likely work the subsequent time.

This lab was created by GKE Helmsman engineers to help you grasp a better understanding of migrating to containers. You can view this demo on Github here. We encourage any and all to contribute to our assets!

Architecture

Configuration 1: a virtual machine running Debian, app deployed directly to the host OS, no containers

screenshot

Configuration 2: a virtual machine running Container-Optimized OS, app deployed into a container

screenshot

Configuration 3: Kubernetes Engine (GKE) platform, many machines running many containers

screenshot

A simple Python Flask web application (Prime-flask) was created for this demonstration which contains two endpoints:

http://<ip>:8080/factorial/ and

http://<ip>:8080/prime/

Examples of use would look like:

curl http://35.227.149.80:8080/prime/10 The sum of all primes less than 10 is 17 curl http://35.227.149.80:8080/factorial/10 The factorial of 10 is 3628800

Also included is a utility to validate a successful deployment.

Setup

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 will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that 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 or private browser window to run this lab. This prevents any 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: If you already have your own personal Google Cloud account or project, do not use it for this lab to avoid extra charges to your 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 pop-up opens for you to select your payment method. On the left is the Lab Details panel with the following:

    • The Open Google 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 Console. 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 from the Lab Details panel and paste it into the Sign in dialog. Click Next.

  4. Copy the Password from the Lab Details panel and paste it into the Welcome dialog. Click Next.

    Important: You must use the credentials from the left panel. Do not use your Google Cloud Skills Boost credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
  5. 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 Cloud Console opens in this tab.

Note: You can view the menu with a list of Google Cloud Products and Services by clicking the Navigation menu at the top-left. Navigation menu icon

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 Activate Cloud Shell icon at the top of the Google Cloud console.

  2. Click Continue.

It takes a few moments to provision and connect to the environment. When you are connected, you are already authenticated, and the project is set to your PROJECT_ID. The output contains a line that declares the PROJECT_ID for this session:

Your Cloud Platform project in this session is set to YOUR_PROJECT_ID

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

Output:

ACTIVE: * ACCOUNT: student-01-xxxxxxxxxxxx@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 = <project_ID>

Example output:

[core] project = qwiklabs-gcp-44776a13dea667a6 Note: For full documentation of gcloud, in Google Cloud, refer to the gcloud CLI overview guide.

Install ApacheBench

Install ApacheBench with the following command:

sudo apt-get update sudo apt-get install apache2-utils

Type "y" when asked to confirm you want to continue.

Verify that the installation was successful:

ab -V

Your output should look like this:

This is ApacheBench, Version 2.3 <$Revision: 1757674 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation,

Task 1. Set your region and zone

Certain Compute Engine resources live in regions and zones. A region is a specific geographical location where you can run your resources. Each region has one or more zones.

Run the following to set a region and zone for your lab (you can use the region/zone that's best for you):

gcloud config set compute/region {{{ project_0.default_region }}} gcloud config set compute/zone {{{ project_0.default_zone }}}

Task 2. Clone the repo

Run the following command to clone the sample code repository:

git clone https://github.com/GoogleCloudPlatform/gke-migration-to-containers.git

Go into the directory of the demo:

cd gke-migration-to-containers

Task 3. Deployment

Switch to the Cloud Shell terminal by clicking Open Terminal.

The infrastructure required by this project can be deployed by executing:

make create

The setup of this demo can take up to 15 minutes to provision. If there is no error the best thing to do is keep waiting. The execution of make create should not be interrupted. While the resources are building, you can check on the progress in the Console by going to Compute Engine > VM instances.

While you're waiting, read ahead to learn what the create.sh script does and what is getting created for you.

You can view gke-migration-to-containers/scripts/create.sh in the code editor.

The make create command calls the create.sh script which performs following tasks:

  1. Packages the deployable Prime-flask application, making it ready to be copied to Cloud Storage.
  2. Creates the container image via Google Cloud Build and pushes it to the private Container Registry (GCR) for your project.
  3. Generates an appropriate configuration for Terraform.
  4. Executes Terraform which creates the scenarios outlined above.

The following are examples of:

Terraform creating single VM, COS VM, and GKE cluster:

screenshot

Terraform outputs showing prime and factorial endpoints for Debian VM and COS system:

screenshot

Kubernetes Cluster and Prime-flask service are up:

screenshot

Test Completed Task

Click Check my progress below to check your lab progress. If you successfully created infrastructure deployment, you'll see an assessment score.

Create Deployment

Task 4. Exploring Prime-Flask Environments

Three different environments have been set up that your Prime-flask app could traverse as it is making its way to becoming a container app living on a single virtual machine to a pod running on a container orchestration platform like Kubernetes.

Once your resources are ready, it would benefit you to explore the systems.

Run the following to go into the vm-webserver machine that has the application running on host OS:

gcloud compute ssh vm-webserver --zone {{{ project_0.default_zone }}}

Type "Y" when asked if you want to continue. Press Enter twice to not use a passphrase.

In this environment there is no isolation, and portability is less efficient. In a sense, the app has access to the whole system, and, depending on other factors, may not have automatic recovery of application if it fails. Scaling up this application may require more virtual machines to spin up and most likely will not be the best use of resources.

List all processes:

ps aux

(Output)

root 882 0.0 1.1 92824 6716 ? Ss 18:41 0:00 sshd: user [priv] user 888 0.0 0.6 92824 4052 ? S 18:41 0:00 sshd: user@pts/0 user 889 0.0 0.6 19916 3880 pts/0 Ss 18:41 0:00 -bash user 895 0.0 0.5 38304 3176 pts/0 R+ 18:41 0:00 ps aux apprunn+ 7938 0.0 3.3 48840 20328 ? Ss Mar19 1:06 /usr/bin/python /usr/local/bin/gunicorn --bind 0.0.0.0:8080 prime-flask-server apprunn+ 21662 0.0 3.9 69868 24032 ? S Mar20 0:05 /usr/bin/python /usr/local/bin/gunicorn --bind 0.0.0.0:8080 prime-flask-server

Then exit:

exit

Run the following to go into the cos-vm machine, where you have docker running the container.

gcloud compute ssh cos-vm --zone {{{ project_0.default_zone }}}

COS is an optimized operating system with small OS footprint, which is part of what makes it secure to run container workloads. It has cloud-init and has Docker runtime preinstalled. This system on its own could be great to run several containers that did not need to be run on a platform that provided higher levels of reliability.

Clone the build files:

git clone https://github.com/GoogleCloudPlatform/gke-migration-to-containers.git cd gke-migration-to-containers/container

Build the docker image locally with the following command:

sudo docker build -t gcr.io/migration-to-containers/prime-flask:1.0.2 .

Run the following command to get a list of processes running on port 8080:

ps aux | grep 8080

You should receive a similar output:

processes

Find the first chronos port number, which will look like the following:

cron-port

Then run the following command to kill the process on the port number, replacing <YOUR_PORT_NUMBER> with the cron port number you found (in the above example, you would use 763):

sudo kill -9 <YOUR_PORT_NUMBER>

Now run the following docker command to retrieve the local image and run it on the vm:

sudo docker run --rm -d --name=appuser -p 8080:8080 gcr.io/migration-to-containers/prime-flask:1.0.2

You can also run ps aux on the host and see the prime-flask running:

ps aux

Notice the docker and container references:

root 626 0.0 5.7 496812 34824 ? Ssl Mar19 0:14 /usr/bin/docker run --rm --name=flaskservice -p 8080:8080 gcr.io/migration-to-containers/prime-flask:1.0.2 root 719 0.0 0.5 305016 3276 ? Sl Mar19 0:00 /usr/bin/docker-proxy -proto tcp -host-ip 0.0.0.0 -host-port 8080 -container-ip 172.17.0.2 -container-port 8080 root 724 0.0 0.8 614804 5104 ? Sl Mar19 0:09 docker-containerd-shim -namespace moby -workdir /var/lib/docker/containerd/daemon/io.containerd.runtime.v1.linux/mo chronos 741 0.0 0.0 204 4 ? Ss Mar19 0:00 /usr/bin/dumb-init /usr/local/bin/gunicorn --bind 0.0.0.0:8080 prime-flask-server chronos 774 0.0 3.2 21324 19480 ? Ss Mar19 1:25 /usr/local/bin/python /usr/local/bin/gunicorn --bind 0.0.0.0:8080 prime-flask-server chronos 14376 0.0 4.0 29700 24452 ? S Mar20 0:05 /usr/local/bin/python /usr/local/bin/gunicorn --bind 0.0.0.0:8080 prime-flask-server

Also notice, if you try to list the python path it does not exist:

ls /usr/local/bin/python

(Output)

ls: cannot access '/usr/local/bin/python': No such file or directory

Docker list containers:

sudo docker ps

(Output)

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES d147963ec3ca gcr.io/migration-to-containers/prime-flask:1.0.2 "/usr/bin/dumb-init …" 39 hours ago Up 39 hours 0.0.0.0:8080->8080/tcp flaskservice

Now you can execute a command to see running process on the container:

sudo docker exec -it $(sudo docker ps |awk '/prime-flask/ {print $1}') ps aux

(Output)

PID USER TIME COMMAND 1 apprunne 0:00 /usr/bin/dumb-init /usr/local/bin/gunicorn --bind 0.0.0.0: 6 apprunne 1:25 {gunicorn} /usr/local/bin/python /usr/local/bin/gunicorn - 17 apprunne 0:05 {gunicorn} /usr/local/bin/python /usr/local/bin/gunicorn - 29 apprunne 0:00 ps aux

Type in "exit":

exit

Next, go into the Kubernetes environment. Here you can run hundreds or thousands of pods that are groupings of containers. Kubernetes is the defacto standard for deploying containers these days. It offers high productivity, reliability, and scalability. Kubernetes makes sure your containers have a home, and if a container happens to fail, it will respawn it again. You can have many machines making up the cluster and in so doing you can spread it across different zones ensuring availability, and resilience to potential issues.

Get cluster configuration:

gcloud container clusters get-credentials prime-server-cluster

Get pods running in the default namespace:

kubectl get pods

(Output)

NAME READY STATUS RESTARTS AGE prime-server-6b94cdfc8b-dfckf 1/1 Running 0 2d5h

See what is running on the pod:

kubectl exec $(kubectl get pods -lapp=prime-server -ojsonpath='{.items[].metadata.name}') -- ps aux

(Output)

PID USER TIME COMMAND 1 apprunne 0:00 /usr/bin/dumb-init /usr/local/bin/gunicorn --bind 0.0.0.0:8080 prime-flask-server 6 apprunne 1:16 {gunicorn} /usr/local/bin/python /usr/local/bin/gunicorn --bind 0.0.0.0:8080 prime-flask-server 8 apprunne 2:52 {gunicorn} /usr/local/bin/python /usr/local/bin/gunicorn --bind 0.0.0.0:8080 prime-flask-server 19 apprunne 0:00 ps aux

As you can see, the python application is now running in a container. The application can't access anything on the host. The container is isolated. It runs in a linux namespace and can't (by default) access files, the network, or other resources running on the VM, in containers or otherwise.

Task 5. Validation

Now that the application is deployed, validate these three deployments by executing:

make validate

Occasionally the APIs take a few moments to complete. Running make validate immediately could potentially appear to fail, but in fact the instances haven't finished initializing. Waiting for a minute or two and retrying the command should resolve any issues.

A successful output will look like this:

Validating Debian VM Webapp... Testing endpoint http://35.227.149.80:8080 Endpoint http://35.227.149.80:8080 is responding. The sum of all primes less than 10 is 17 The factorial of 10 is 3628800 Validating Container OS Webapp... Testing endpoint http://35.230.123.231:8080 Endpoint http://35.230.123.231:8080 is responding. The sum of all primes less than 10 is 17 The factorial of 10 is 3628800 Validating Kubernetes Webapp... Testing endpoint http://35.190.89.136 Endpoint http://35.190.89.136 is responding. The sum of all primes less than 10 is 17 The factorial of 10 is 3628800

Of course, the IP addresses will likely differ for your deployment.

Task 6. Load Testing

In Cloud Shell click the + to open a new Cloud Shell tab.

Execute the following, for each resource, replacing <IP_ADDRESS> with the IP address and <PORT> with the port from your validation output in the previous step. Note that the Kubernetes deployment runs on port 80, while the other two deployments run on port 8080:

ab -c 120 -t 60 http://<IP_ADDRESS>:<PORT>/prime/10000

ApacheBench (ab) will execute 120 concurrent requests against the provided endpoint for 1 minute. The demo application's replica is insufficiently sized to handle this volume of requests.

This can be confirmed by reviewing the output from the ab command. If you see a Failed requests value of greater than 0, this means that the server couldn't respond successfully to this load:

screenshot

Note: You may not see failures on all three of your resources.

Test Completed Task

Click Check my progress below to check your lab progress. If you successfully performed load testing, you'll see an assessment score.

Load Testing

One way to ensure that your system has the capacity to handle this type of traffic is by scaling up. In this case, scale the service horizontally.

In the Debian and COS architectures, horizontal scaling would include:

  1. Creating a load balancer.
  2. Spinning up additional instances.
  3. Registering them with the load balancer.

This is an involved process and is out of scope for this demonstration.

For the third (Kubernetes) deployment, the process is far easier.

In your 1st Cloud Shell tab, run the following:

kubectl scale --replicas 3 deployment/prime-server

Test Completed Task

Click Check my progress below to check your lab progress. If you successfully scaled deployment, you'll see an assessment score.

Scale prime-server deployment

After allowing 30 seconds for the replicas to initialize, re-run the load test:

ab -c 120 -t 60 http://<IP_ADDRESS>:<PORT>/prime/10000

Notice how the Failed requests is now 0. This means that all of the 10,000+ requests were successfully answered by the server:

screenshot

Task 7. Tear Down

Although Qwiklabs will clean up all resources provided to you for this lab, it's good to know how to clean up your own environment.

Run the following in your 1st Cloud Shell tab:

make teardown

It will run terraform destroy which will destroy all of the resources created for this demonstration.

screenshot

Congratulations!

Finish Your Quest

Enterprise-Customers.png

This self-paced lab is part of the Qwiklabs Google Kubernetes Engine Best Practices: Security Quest. A Quest is a series of related labs that form a learning path. Completing this Quest earns you the badge above, to recognize your achievement. You can make your badge (or badges) public and link to them in your online resume or social media account. Enroll in this Quest and get immediate completion credit if you've taken this lab. See other available Qwiklabs Quests.

Take your next lab

Continue your Quest with How to Use a Network Policy on Kubernetes Engine, or check out these suggestion:

Next Steps / Learn More

Google Cloud training and certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated Aug 4, 2022
Lab Last Tested Aug 4, 2022

Copyright 2022 Google LLC. This software is provided as-is, without warranty or representation for any use or purpose. Your use of it is subject to your agreement with Google.