arrow_back

Using a Global Load Balancer with Cloud Run [APPRUN]

로그인 가입
지식을 테스트하고 커뮤니티와 공유하기
done
700개 이상의 실무형 실습, 기술 배지, 과정에 액세스

Using a Global Load Balancer with Cloud Run [APPRUN]

실습 1시간 universal_currency_alt 크레딧 5개 show_chart 입문
info 이 실습에는 학습을 지원하는 AI 도구가 통합되어 있을 수 있습니다.
지식을 테스트하고 커뮤니티와 공유하기
done
700개 이상의 실무형 실습, 기술 배지, 과정에 액세스

Google Cloud Self-Paced Labs

Overview

The External HTTP(S) Load Balancer architecture

Serverless Network Endpoint Groups (NEGs) allow you to use Google Cloud serverless apps with external HTTP(S) Load Balancing. After you have configured a load balancer with the serverless NEG backend, requests to the load balancer are routed to the serverless app backend.

In this lab you will learn how to set up and use an HTTP global load balancer with Cloud Run.

Objectives

In this lab, you learn to:

  • Enable the Cloud Run API.
  • Create and deploy a sample application in Cloud Run.
  • Configure a Serverless Network Engpoint Group (NEG).
  • Create a global load balancer with a serverless NEG backend.
  • Route requests for the sample application through the global load balancer.

Prerequisites

These labs are based on intermediate knowledge of Google Cloud. While the steps required are covered in the content, it would be helpful to have familiarity with any of the following products:

  • HTTP load balancer
  • Cloud Run

Setup and requirements

Before you click the Start Lab button

Note: 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 Qwiklabs 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.

What you need

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
  • Time to complete the lab.
Note: If you already have your own personal Google Cloud account or project, do not use it for this lab. Note: If you are using a Pixelbook, open an Incognito window to run this lab.

How to start your lab and sign in to the 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 a panel populated with the temporary credentials that you must use for this lab.

    Credentials panel

  2. Copy the username, and then click Open Google Console. The lab spins up resources, and then opens another tab that shows the Choose an account page.

    Note: Open the tabs in separate windows, side-by-side.
  3. On the Choose an account page, click Use Another Account. The Sign in page opens.

    Choose an account dialog box with Use Another Account option highlighted

  4. Paste the username that you copied from the Connection Details panel. Then copy and paste the password.

Note: You must use the credentials from the Connection Details panel. Do not use your Google Cloud Skills Boost credentials. If you have your own Google Cloud account, do not use it for this lab (avoids incurring charges).
  1. 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. Cloud Console Menu

Activate Google Cloud Shell

Google 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.

Google Cloud Shell provides command-line access to your Google Cloud resources.

  1. In Cloud console, on the top right toolbar, click the Open Cloud Shell button.

    Highlighted Cloud Shell icon

  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. For example:

Project ID highlighted in the Cloud Shell Terminal

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

  • You can list the active account name with this command:
gcloud auth list

Output:

Credentialed accounts: - @.com (active)

Example output:

Credentialed accounts: - google1623327_student@qwiklabs.net
  • You can list the project ID with this command:
gcloud config list project

Output:

[core] project =

Example output:

[core] project = qwiklabs-gcp-44776a13dea667a6 Note: Full documentation of gcloud is available in the gcloud CLI overview guide .

Basic Linux Commands

Below you will find a reference list of a few very basic Linux commands which may be included in the instructions or code blocks for this lab.

Command --> Action . Command --> Action
mkdir (make directory) create a new folder . cd (change directory) change location to another folder
ls (list ) list files and folders in the directory . cat (concatenate) read contents of a file without using an editor
apt-get update update package manager library . ping signal to test reachability of a host
mv (move ) moves a file . cp (copy) makes a file copy
pwd (present working directory ) returns your current location . sudo (super user do) gives higher administration privileges

Task 1. Configure the environment

Cloud Run requires some environmental configuration before we begin. In this section, you enable the Cloud Run API and set the compute region.

  1. Enable Cloud Run API:
gcloud services enable run.googleapis.com

If you are asked to authorize the use of your credentials, do so.

You should then see a successful message similar to this one:

Operation "operations/acf.cc11852d-40af-47ad-9d59-477a12847c9e" finished successfully. Note: You can also enable the API using the APIs & Services section of the console.
  1. Set the compute and run regions. Cloud Run requires knowledge of the region in which it will be deployed:
gcloud config set compute/region {{{project_0.default_region|REGION}}} gcloud config set run/region {{{project_0.default_region|REGION}}}
  1. Create a LOCATION environment variable:
LOCATION={{{project_0.default_region|REGION}}}

This lab also requires the gcloud command line tool for Google Cloud Platform. However, the gcloud command line tool comes pre-installed on Cloud Shell so we will not need to configure it in this lab.

Task 2. Write a simple application

For this lab, we will create a simple Cloud Run Python "Hello, World" app and deploy it as a Cloud Run service in the region. This simple app will become the target for an external HTTP load balancer which will use a serverless NEG backend to route requests to that service.

  1. In Cloud Shell create a new directory named helloworld, then move your view into that directory:
mkdir helloworld && cd helloworld

Next you'll be creating and editing files.

  1. To edit files, use vi, emac, nano or the Cloud Shell Editor by clicking on the pencil icon in Cloud Shell ("Open Editor").

The Open Editor button highlighted in the UI.

When you open the Cloud Shell Editor, it will show your user's home directory, NOT the directory you are seeing in the terminal.

  1. Be sure to click on the "helloworld" folder to be certain you are in the correct directory before you create the following two files.

  2. Create a main.py file, then add the following content to it:

import os from flask import Flask app = Flask(__name__) @app.route("/") def hello_world(): name = os.environ.get("NAME", "World") return "Hello {}!".format(name) if __name__ == "__main__": app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))

This code responds to requests on port 8080 with a "Hello World" greeting.

Your app is now finished and ready to be containerized and uploaded to Container Registry.

Note: You can use languages other than Python to get started with Cloud Run. You can find instructions for Go, Python, Java, PHP, Ruby, Shell scripts, and others in the Cloud Run documentation.

Task 3. Containerize your app and upload it to Container Registry (Artifact Registry)

  1. To containerize the sample app you just made, create a new file named Dockerfile in the same directory as the main.py file, and add the following content:
# Use the official lightweight Python image. # https://hub.docker.com/_/python FROM python:3.9-slim # Allow statements and log messages to immediately appear in the Knative logs ENV PYTHONUNBUFFERED True # Copy local code to the container image. ENV APP_HOME /app WORKDIR $APP_HOME COPY . ./ # Install production dependencies. RUN pip install Flask gunicorn # Run the web service on container startup. Here we use the gunicorn # webserver, with one worker process and 8 threads. # For environments with multiple CPU cores, increase the number of workers # to be equal to the cores available. # Timeout is set to 0 to disable the timeouts of the workers to allow Cloud Run to handle instance scaling. CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 main:app

This Python Dockerfile starts a Gunicorn web server which listens on the port defined by the PORT environmental variable set in the main.py file (port 8080).

  1. Now, build your container image using Cloud Build, by running the following command from the directory containing the Dockerfile:
gcloud builds submit --tag gcr.io/$GOOGLE_CLOUD_PROJECT/helloworld

Upon success, you will see a SUCCESS message containing the image name (gcr.io/PROJECT-ID/helloworld). The image is now stored in Container Registry and can be deployed in the next task.

Note: You can ignore any warning while building the container image using Cloud Build.

Task 4. Deploy your container to Cloud Run

Now that we have our containerized image, we will need to use the gcloud command below to deploy it to Cloud Run.

  1. Replace PROJECT-ID with your GCP project ID. You can view your project ID by running the command gcloud config get-value project.
gcloud run deploy --image gcr.io/$GOOGLE_CLOUD_PROJECT/helloworld
  1. The API should already be enabled, but if you are prompted to enable the API, Reply y.

  2. You will then be prompted for the service name: press Enter to accept the default name, helloworld.

  3. If prompted for region: in this case, select .

  4. You will be prompted to allow unauthenticated invocations: respond y.

Wait a few moments until the deployment is complete. Upon success, the command line displays the service URL.

  1. Visit your deployed container by opening the service URL in a web browser.

Task 5. Reserve an external IP address

Now that your services are up and running, you need to set up a global static external IP address that your customers use to reach your load balancer.

A static external IP address provides a single address to point your serverless app to. Reserving an IP address would also be essential if you were using a custom domain for your serverless app.

  1. Use the following command to reserve your static IP address:
gcloud compute addresses create example-ip \ --ip-version=IPV4 \ --global
  1. To display the IP address that was just reserved, use:
gcloud compute addresses describe example-ip \ --format="get(address)" \ --global
  1. Note this IP address, because you will need it later.

Task 6. Create the external HTTP load balancer

Load balancers use a serverless Network Endpoint Group (NEG) backend to direct requests to a serverless Cloud Run service.
So, let's first create our serverless NEG for our serverless Python app created earlier in this lab.

  1. To create a serverless NEG with a Cloud Run service, enter the following in Cloud Shell:
gcloud compute network-endpoint-groups create myneg \ --region=$LOCATION \ --network-endpoint-type=serverless \ --cloud-run-service=helloworld
  1. Now, we need to create a backend service:
gcloud compute backend-services create mybackendservice \ --global
  1. And then add the serverless NEG as a backend to this backend service:
gcloud compute backend-services add-backend mybackendservice \ --global \ --network-endpoint-group=myneg \ --network-endpoint-group-region=$LOCATION
  1. Finally, create a URL map to route incoming requests to the backend service:
gcloud compute url-maps create myurlmap \ --default-service mybackendservice

If you had more than one backend service, you could use host rules to direct requests to different services based on the host name, or you could set up path matchers to direct requests to different services based on the request path. None of this is necessary here because we have only created one backend service for this lab.

  1. Now, create a target HTTP(S) proxy to route requests to your URL map:
gcloud compute target-http-proxies create mytargetproxy \ --url-map=myurlmap
  1. Create a global forwarding rule to route incoming requests to the proxy:
gcloud compute forwarding-rules create myforwardingrule \ --address=example-ip \ --target-http-proxy=mytargetproxy \ --global \ --ports=80

Task 7. Test your external HTTP load balancer

  • You can test your HTTP load balancer by going to http://IP_ADDRESS, where IP_ADDRESS is the load balancer's IP address you reserved earlier in this lab. When you open this URL, you should see the helloworld service homepage.

Congratulations!

Over this course of this lab, you have learned how to use an HTTP global load balancer with a Cloud Run application.

  • Deploy a simple Cloud Run service
  • Expose this service to the internet using an external IP address
  • Create a global HTTP load balancer for the service

Next steps / Learn more

Follow the Serverless Expeditions video series to learn more about how to utilise these products within your project.

  • Cloud Run
  • Cloud Build
  • Cloud Functions

Manual Last Updated February 23, 2024

Lab Last Tested February 23, 2024

Copyright 2022 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.

현재 이 콘텐츠를 이용할 수 없습니다

이용할 수 있게 되면 이메일로 알려드리겠습니다.

감사합니다

이용할 수 있게 되면 이메일로 알려드리겠습니다.