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
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.
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.
On the Choose an account page, click Use Another Account. The Sign in page opens.
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).
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.
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.
In Cloud console, on the top right toolbar, click the Open Cloud Shell button.
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:
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:
[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.
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.
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}}}
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.
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.
To edit files, use vi, emac, nano or the Cloud Shell Editor by clicking on the pencil icon in Cloud Shell ("Open Editor").
When you open the Cloud Shell Editor, it will show your user's home directory, NOT the directory you are seeing in the terminal.
Be sure to click on the "helloworld" folder to be certain you are in the correct directory before you create the following two files.
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)
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).
Now, build your container image using Cloud Build, by running the following command from the directory containing the Dockerfile:
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.
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
The API should already be enabled, but if you are prompted to enable the API, Reply y.
You will then be prompted for the service name: press Enter to accept the default name, helloworld.
If prompted for region: in this case, select .
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.
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.
Use the following command to reserve your static IP address:
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.
To create a serverless NEG with a Cloud Run service, enter the following in Cloud Shell:
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.
Now, create a target HTTP(S) proxy to route requests to your URL map:
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
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.
Labs erstellen ein Google Cloud-Projekt und Ressourcen für einen bestimmten Zeitraum
Labs haben ein Zeitlimit und keine Pausenfunktion. Wenn Sie das Lab beenden, müssen Sie von vorne beginnen.
Klicken Sie links oben auf dem Bildschirm auf Lab starten, um zu beginnen
Privates Surfen verwenden
Kopieren Sie den bereitgestellten Nutzernamen und das Passwort für das Lab
Klicken Sie im privaten Modus auf Konsole öffnen
In der Konsole anmelden
Melden Sie sich mit Ihren Lab-Anmeldedaten an. Wenn Sie andere Anmeldedaten verwenden, kann dies zu Fehlern führen oder es fallen Kosten an.
Akzeptieren Sie die Nutzungsbedingungen und überspringen Sie die Seite zur Wiederherstellung der Ressourcen
Klicken Sie erst auf Lab beenden, wenn Sie das Lab abgeschlossen haben oder es neu starten möchten. Andernfalls werden Ihre bisherige Arbeit und das Projekt gelöscht.
Diese Inhalte sind derzeit nicht verfügbar
Bei Verfügbarkeit des Labs benachrichtigen wir Sie per E-Mail
Sehr gut!
Bei Verfügbarkeit kontaktieren wir Sie per E-Mail
Es ist immer nur ein Lab möglich
Bestätigen Sie, dass Sie alle vorhandenen Labs beenden und dieses Lab starten möchten
Privates Surfen für das Lab verwenden
Nutzen Sie den privaten oder Inkognitomodus, um dieses Lab durchzuführen. So wird verhindert, dass es zu Konflikten zwischen Ihrem persönlichen Konto und dem Teilnehmerkonto kommt und zusätzliche Gebühren für Ihr persönliches Konto erhoben werden.
Cloud Run allows you to specify which revisions should receive traffic and to specify traffic percentages that are received by a revision.