GSP041

Overview
Google Cloud's Internal Load Balancer lets you load balance TCP/UDP traffic without exposing your VM's public IP to the Internet.
This example uses a distributed architecture; a Web Tier service connects to an Internal Tier which is distributed across several machines:

In this lab, you create a public-facing web server to serve the result of several "complex" calculations, in this case, calculating prime numbers. The prime numbers are each calculated by a micro service that is run on a managed instance group and scaled automatically.
What you'll do
- Learn about the components of an Internal Load Balancer
- Create a managed instance group of backends
- Point an internal load balancer to the backends
- Test the internal load balancer, and call it from a public facing web server
Prerequisites
- Basic knowledge of Compute Engine
- Basic networking and TCP/IP knowledge
- Basic Unix/Linux command line knowledge
- Some knowledge about VPCs is helpful, for example from the other labs in this series
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
-
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
-
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.
-
If necessary, copy the Username below and paste it into the Sign in dialog.
{{{user_0.username | "Username"}}}
You can also find the Username in the Lab Details pane.
-
Click Next.
-
Copy the Password below and paste it into the Welcome dialog.
{{{user_0.password | "Password"}}}
You can also find the Password in the Lab Details pane.
-
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.
-
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.
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.
-
Click Activate Cloud Shell
at the top of the Google Cloud console.
-
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, . The output contains a line that declares the Project_ID for this session:
Your Cloud Platform project in this session is set to {{{project_0.project_id | "PROJECT_ID"}}}
gcloud
is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.
- (Optional) You can list the active account name with this command:
gcloud auth list
- Click Authorize.
Output:
ACTIVE: *
ACCOUNT: {{{user_0.username | "ACCOUNT"}}}
To set the active account, run:
$ gcloud config set account `ACCOUNT`
- (Optional) You can list the project ID with this command:
gcloud config list project
Output:
[core]
project = {{{project_0.project_id | "PROJECT_ID"}}}
Note: For full documentation of gcloud
, in Google Cloud, refer to the gcloud CLI overview guide.
Set the region and zone
- Set the project region and zone for this lab:
gcloud config set compute/region {{{project_0.default_region | Region}}}
gcloud config set compute/zone {{{project_0.default_zone | Zone}}}
- Create a variable for region:
export REGION={{{project_0.default_region | Region}}}
- Create a variable for zone:
export ZONE={{{project_0.default_zone | Zone}}}
Learn more from the Regions & Zones documentation.
Note: When you run gcloud
on your own machine, the config settings are persisted across sessions. But in Cloud Shell, you need to set this for every new session or reconnection.
Task 1. Create a virtual environment
Python virtual environments are used to isolate package installation from the system.
- Install the
virtualenv
environment:
sudo apt-get install -y virtualenv
- Build the virtual environment:
python3 -m venv venv
- Activate the virtual environment:
source venv/bin/activate
Task 2. Create Backend Managed Instance Group
Use gcloud
in Cloud Shell to set up the Managed Instance Group for calculating the prime numbers.
Create the startup script which includes a simple web server in Python that will return True or False depending on if a number is prime or not.
- Start by creating your
backend.sh
script in the home directory:
touch ~/backend.sh
- Click the Open Editor by clicking the icon at the top of the Cloud Shell. If prompted click Open in a new window.

Note: If you don't see the Code Editor icon, close the left panel by clicking the Navigation menu icon.
Launching the Code Editor moves Cloud Shell to a new window and opens the Code Editor. After a few seconds the workspace comes up.
-
Select the backend.sh
file in the left pane.
-
Now add the following script into the editor on the right:
sudo chmod -R 777 /usr/local/sbin/
sudo cat << EOF > /usr/local/sbin/serveprimes.py
import http.server
def is_prime(a): return a!=1 and all(a % i for i in range(2,int(a**0.5)+1))
class myHandler(http.server.BaseHTTPRequestHandler):
def do_GET(s):
s.send_response(200)
s.send_header("Content-type", "text/plain")
s.end_headers()
s.wfile.write(bytes(str(is_prime(int(s.path[1:]))).encode('utf-8')))
http.server.HTTPServer(("",80),myHandler).serve_forever()
EOF
nohup python3 /usr/local/sbin/serveprimes.py >/dev/null 2>&1 &
-
Click File > Save.
-
Click Open Terminal on the toolbar of Cloud Shell. Enter the following command to create the instance template for a simple instance with no external IP address:
gcloud compute instance-templates create primecalc \
--metadata-from-file startup-script=backend.sh \
--no-address --tags backend --machine-type=e2-medium
- Now open the firewall to port
80
:
gcloud compute firewall-rules create http --network default --allow=tcp:80 \
--source-ranges {{{project_0.startup_script.selected_cidr | IP}}} --target-tags backend
Click Check my progress below to verify you're on track in this lab.
Create instance template and open firewall on port 80
- Next create the instance group:
gcloud compute instance-groups managed create backend \
--size 3 \
--template primecalc \
--zone $ZONE
- And set it to auto scale based on the CPU:
gcloud compute instance-groups managed set-autoscaling backend \
--target-cpu-utilization 0.8 --min-num-replicas 3 \
--max-num-replicas 10 --zone $ZONE
- When this finishes running, go back to the Console tab. Navigate to the VM instance: Compute Engine > VM instances. You now see three backends:

The backends are now ready to serve traffic.
Click Check my progress below to verify you're on track in this lab.
Create the instance group and set it to auto-scale based on the CPU
Task 3. Setup internal load balancer
Now set up the Internal Load Balancer and link it with the instance group created earlier.
An internal load balancer consists of a:
- Forwarding rule which binds an internal IP address.
- Backend service (which is regional) linking to one or more backend instance groups (which are zonal).
- Health check attached to the backend service that determines which instances can receive new connections.
The following diagram shows how instances are load balanced using multiple instances in multiple backend groups in different zones.

You create a single backend service in this lab.
A health check is needed to balance between healthy instances only.
- Since the HTTP service is provided, see if a 200 response on a specific URL path (in this case /2 to check if 2 is prime) is populated:
gcloud compute health-checks create http ilb-health --request-path /2
- Create a backend service:
gcloud compute backend-services create prime-service \
--load-balancing-scheme internal --region=$REGION \
--protocol tcp --health-checks ilb-health
- Add the instance group:
gcloud compute backend-services add-backend prime-service \
--instance-group backend --instance-group-zone=$ZONE \
--region=$REGION
- Now create the forwarding rule to finalize the load balancer setup with a static IP of :
gcloud compute forwarding-rules create prime-lb \
--load-balancing-scheme internal \
--ports 80 --network default \
--region=$REGION --address {{{project_0.startup_script.selected_forwarding_rule_cidr | IP}}} \
--backend-service prime-service
The service is now able to be queried via the internal address .
Click Check my progress below to verify you're on track in this lab.
Setup internal load balancer
Task 4. Test the load balancer
Duration is 1 min
To test the load balancer, you need to create a new instance in the same network as the internal load balancer and SSH into it. That is because the cloud shell lives outside the project network you created.
- Using
gcloud
in Cloud Shell, create the new instance:
gcloud compute instances create testinstance \
--machine-type=e2-standard-2 --zone $ZONE
- Then SSH into it:
gcloud compute ssh testinstance --zone $ZONE
If prompted, type Y and press Enter twice to proceed.
- Check if a few numbers are prime by querying the IP of the load balancer with the curl command:
curl {{{project_0.startup_script.selected_forwarding_rule_cidr | IP}}}/2
curl {{{project_0.startup_script.selected_forwarding_rule_cidr | IP}}}/4
curl {{{project_0.startup_script.selected_forwarding_rule_cidr | IP}}}/5
The output does not come with a carriage return, so you see it straight in front of the next command line like this:
user@testinstance:~$ curl {{{project_0.startup_script.selected_forwarding_rule_cidr | IP}}}/2
Trueuser@testinstance:~$ curl {{{project_0.startup_script.selected_forwarding_rule_cidr | IP}}}/4
Falseuser@testinstance:~$ curl {{{project_0.startup_script.selected_forwarding_rule_cidr | IP}}}/5
Trueuser@testinstance:~$ exit
The service responded correctly: that 2 and 5 are prime numbers, but 4 is not.
- Leave the test instance:
exit
- Then delete it:
gcloud compute instances delete testinstance --zone=$ZONE
- Type in Y to confirm the deletion.
Task 5. Create a public facing web server
Duration is 8 min
Create a public facing web server that returns a matrix based on a bunch of prime number calculations balanced via the internal load balancer.
You could make this an auto-scaling managed instance group load balanced by the external HTTP(S) load balancer, but for the sake of simplicity, create a single serving instance.
First, create the startup script for the front end.
- Start by creating your
frontend.sh
script in the home directory:
touch ~/frontend.sh
- You should still see the Code Editor open. But if not, launch the Code Editor by selecting it in the shell:

After a few seconds the workspace comes up.
- Now add this script into the editor on the right:
sudo chmod -R 777 /usr/local/sbin/
sudo cat << EOF > /usr/local/sbin/getprimes.py
import urllib.request
from multiprocessing.dummy import Pool as ThreadPool
import http.server
PREFIX="http://{{{project_0.startup_script.selected_forwarding_rule_cidr | IP}}}/" #HTTP Load Balancer
def get_url(number):
return urllib.request.urlopen(PREFIX+str(number)).read().decode('utf-8')
class myHandler(http.server.BaseHTTPRequestHandler):
def do_GET(s):
s.send_response(200)
s.send_header("Content-type", "text/html")
s.end_headers()
i = int(s.path[1:]) if (len(s.path)>1) else 1
s.wfile.write("<html><body><table>".encode('utf-8'))
pool = ThreadPool(10)
results = pool.map(get_url,range(i,i+100))
for x in range(0,100):
if not (x % 10): s.wfile.write("<tr>".encode('utf-8'))
if results[x]=="True":
s.wfile.write("<td bgcolor='#00ff00'>".encode('utf-8'))
else:
s.wfile.write("<td bgcolor='#ff0000'>".encode('utf-8'))
s.wfile.write(str(x+i).encode('utf-8')+"</td> ".encode('utf-8'))
if not ((x+1) % 10): s.wfile.write("</tr>".encode('utf-8'))
s.wfile.write("</table></body></html>".encode('utf-8'))
http.server.HTTPServer(("",80),myHandler).serve_forever()
EOF
nohup python3 /usr/local/sbin/getprimes.py >/dev/null 2>&1 &
-
Click File > Save.
-
In Cloud Shell create an instance running this web server:
gcloud compute instances create frontend --zone=$ZONE \
--metadata-from-file startup-script=frontend.sh \
--tags frontend --machine-type=e2-standard-2
- Open the firewall for the front end:
gcloud compute firewall-rules create http2 --network default --allow=tcp:80 \
--source-ranges 0.0.0.0/0 --target-tags frontend
-
In the Navigation menu, click Compute Engine > VM instances. Refresh your browser if you don't see the frontend instance.
-
Open the External IP for the frontend in your browser:

You should see a matrix like this, showing all prime numbers, up to 100, in green:

- Try adding a number to the path, like http://your-ip/10000, to see all prime numbers starting from that number.

Note: The example startup script is not effectively calculating prime numbers. It also doesn't have error detection or correction algorithms. Adding large numbers to the path will make the service time out.
Click Check my progress below to verify you're on track in this lab.
Create a public facing web server
Congratulations!
You have created a frontend web server which runs 100 queries to a load balanced internal back end through a front end request.
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 Date February 5, 2025
Lab Last Tested Date February 5, 2025
Copyright 2025 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.