# List active account namegcloudauthlist# List project IDgcloudconfiglistproject
Set Up Network Load Balancers
Task 1 : Set the defualt region and zone for all resources
Set the default region:
gcloud config set compute/region Region
Set the default zone:
gcloud config set compute/zone Zone
Task 2 : Create multiple web server instances
Create a virtual machine, www1, in your default zone using the following code :
Create a virtual machine, www2, in your default zone using the following code :
Create a virtual machine, www3, in your default zone using the following code :
Create a firewall rule to allow external traffic to the VM instances :
List your instances. See IP addresses in EXTERNAL_IP column :
Verify each instance is running with curl replacing [IP_ADDRESS] with external IP address for each of your VMs :
Task 3 : Configure the load balancing service
Create a static external IP address for your load balancer:
Output:
Add a legacy HTTP health check resource:
Task 4 : Create the target pool and forwarding rule
Run the following to create the target pool and use the health check, which is required for the service to function:
Add the instances you created earlier to the pool:
Add a forwarding rule:
Task 5 : Send traffic to your instances
Enter the following command to view the external IP address of the www-rule forwarding rule used by the load balancer:
Access the external IP address:
Show the external IP address:
Use the curl command to access the external IP address, replacing IP_ADDRESS with an external IP address from the previous command:
The response from the curl command alternates randomly among the three instances. If your response is initially unsuccessful, wait approximately 30 seconds for the configuration to be fully loaded and for your instances to be marked healthy before trying again.
Use Ctrl + C to stop running the command.
Set Up Application Load Balancers
Task 1 : Set the default region and zone for all resources
Set the default region :
Set the default zone :
Task 2 : Create multiple web server instances
Create a virtual machine, www1, in your default zone using the following code:
Create a virtual machine, www2, in your default zone using the following code:
Create a virtual machine, www3, in your default zone.
Create a firewall rule to allow external traffic to the VM instances:
List your instances. See IP addresses in EXTERNAL_IP column :
Verify each instance is running with curl replacing [IP_ADDRESS] with external IP address for each of your VMs :
Task 3 : Create an Application Load Balancer
Create the Load Balancer template
Create a managed instance group based on the template
Create the fw-allow-health-check firewall rule
Note: The ingress rule allows traffic from the Google Cloud health checking systems (130.211.0.0/22 and 35.191.0.0/16). This lab uses the target tag allow-health-check to identify the VMs
Set up a global static external IP address that your customers use to reach your load balancer :
Notice that the IPv4 address that was reserved :
Note: Save this IP address, as you need to refer to it later in this lab.
Create a health check for the load balancer (to ensure that only healthy backends are sent traffic) :
Create a backend service
Add your instance group as the backend to the backend service :
Create a URL map to route the incoming requests to the default backend service :
Note: URL map is a Google Cloud configuration resource used to route requests to backend services or backend buckets. For example, with an external Application Load Balancer, you can use a single URL map to route requests to different destinations based on the rules configured in the URL map: Requests for https://example.com/video go to one backend service. Requests for https://example.com/audio go to a different backend service. Requests for https://example.com/images go to a Cloud Storage backend bucket. Requests for any other host and path combination go to a default backend service.
Create a target HTTP proxy to route requests to your URL map:
Create a global forwarding rule to route incoming requests to the proxy:
Note: A forwarding rule and its corresponding IP address represent the frontend configuration of a Google Cloud load balancer.
Task 4 : Test traffic sent to your instances
On the Google Cloud console in the Search field type Load balancing, then choose Load balancing from the search results.
Click on the load balancer that you just created, web-map-http.
In the Backend section, click on the name of the backend and confirm that the VMs are Healthy. If they are not healthy, wait a few moments and try reloading the page.
When the VMs are healthy, test the load balancer using a web browser, going to http://IP_ADDRESS/, replacing IP_ADDRESS with the load balancer's IP address that you copied previously.
Note: This may take three to five minutes. If you do not connect, wait a minute, and then reload the browser.
Your browser should render a page with content showing the name of the instance that served the page, along with its zone (for example, Page served from: lb-backend-group-xxxx).
User an Internal Application Load Balancer
Set the project region and zone for this tab :
Task 1 : Create a Virtual Environment
Install the virtualev environment
Build the virtual environment:
Activate the virtual environment:
Enable Gemini Code Assist in the Cloud Shell IDE
In Cloud Shell, enable the Gemini for Google Cloud API with the following command:
Click Open Editor on the Cloud Shell toolbar.
Note: To open the Cloud Shell Editor, click Open Editor on the Cloud Shell toolbar. You can switch between Cloud Shell and the code Editor by clicking Open Editor or Open Terminal, as required.
Click Cloud Code - No Project in the status bar at the bottom of the screen.
Authorize the plugin if necessary. If a project is not automatically selected, click Select a Google Cloud Project, and choose Project ID.
Verify that your Google Cloud project (Project ID) displays in the Cloud Code status message in the status bar.
Task 2 : Create a backend managed instance group
Google cloud can automatically create and maintain identical copies of your service using "Managed instance group"
Create the startup script
Create your backend.sh script in the home directory :
Click Open Editor icon in Cloud Shell toolbar. Open in a new window
Select the backend.sh file in the File Explorer pane
Add the following script into the Editor :
Click File > Save but do not close the File
Click the Gemini Code Assist: Smart Actions icon and select Explain this
Replace the prefilled prompt with the following and click Send :
Create the instance template
Create the instance template primecalc:
--no-address, meaning these backend VMs won't have public internet access for security reasons.
Open the firewall
Open the firewall to port 80 :
Create the instance group
Create the managed instance group named backend. Start off with 3 instances :
Navigate to Compute Engine > VM instances. The backends are now ready to serve traffic.
Task 3 : Set up the internal load balancer
An Internal Load Balancer consists of 3 main parts :
Forwarding Rule : This is the actual private IP address that other internal services send requests to. It "forwards" traffic to your backend service.
Backend Service : This defines how the load balancer distributes traffic to your VM instances. It also includes the health check.
Health Check : This is a continuous check that monitors the "health" of your backend VMs. The load balancer only sends traffic to machines that are passing their health checks, ensuring your service is always available.
Create a health check
A health check is needed to make sure the load balancer only sends traffic to healthy instances. Your backend service is an HTTP server, so run the following command to check if it responds with a "200 OK" on a specific URL path (in this case, /2 to check if 2 is prime):
Create a backend service
Create the backend service named prime-service:
This service ties the health check to the instance group.
Add the instance group to the backend service
Run the following command to connect your backend instance group to the prime-service backend service. This tells the load balancer which machines it should manage:
Create the forwarding rule
Finally, run the following command to create a forwarding rule named prime-lb with a static IP of IP:
Your internal "prime number calculation" service is now fully set up and ready to be queried via its internal IP address.
Task 4 : Test the load balancer
To test the load balancer, you need to create a new VM instance in the same network as your internal Application Load Balancer. It's only accessible from within your private cloud network, not directly from Cloud Shell (which lives outside this specific network).
Create a simple test instance:
Run the following command to SSH into it
If prompted, type Y and press Enter twice to proceed.
Query the load balancer
From inside the test instance, run the following curl commands to ask your internal Application Load Balancer's IP address if a few numbers are prime:
The output shows True or False right next to your command line.
Run the following command to leave the test instance
Run the following command to delete it because it's not needed any more
Type in Y to confirm the deletion.
Task 5 : Create a public-facing web server
Create a public-facing web server that users the internal "prime number calculator" service (via the internal Application Load Balancer) to display a matrix of prime numbers.
Run the following command to create startup script for this public-facing "frontend" in the home directory :
Launch the Code Editor by selecting it in the shell
Select the frontend.sh file in the file Explorer pane
Now add the following script into the Editor :
Click File > Save. Do not close the file
Click the Gemini Code Assist: Smart Actions icon and select Explain this
Replace the prefilled prompt with the following and click Send :
Create the frontend instance
Run the following code to create an instance named frontend that runs this web server
Open the firewall for the frontend
This is a public-facing server, so you need to run the following command to open its firewall to allow traffic from anywhere on the internet (0.0.0.0/0) on port 80:
In Navigation menu, click Compute Engine > VM instances. Refresh your browser if you dont 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.
Implement Load Balancing on Compute Enginer: Challenge Lab
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 &
As an Application Developer at Cymbal AI, explain the backend.sh startup script to a new team member. This script is used to run a small Python web server written in a Python file serveprimes.py. Provide a detailed breakdown of the script's key components and explain the function of each command.
For the suggested improvements, don't make any changes to the file's content.
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://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 &
You are an Application Developer at Cymbal AI. A new team member needs help understanding this startup script, which is used to run a public-facing web server written in the Python file getprimes.py. Explain the frontend.sh script in detail. Break down its key components, the commands used, and their function within the script.
For suggested improvements, do not make any changes to the file's content.