gcloud compute instance-templates create lb-backend-template \
--region=us-west3 \
--network=default \
--subnet=default \
--tags=allow-health-check \
--machine-type=e2-medium \
--image-family=debian-11 \
--image-project=debian-cloud \
--metadata=startup-script="cat << EOF > startup.sh
#! /bin/bash
apt-get update
apt-get install -y nginx
service nginx start
sed -i -- 's/nginx/Google Cloud Platform - '"\$HOSTNAME"'/'
/var/www/html/index.nginx-debian.html
EOF"
Create a managed instance group based on the template:
gcloud compute instance-groups managed create lb-backend-group \
--template=lb-backend-template --size=2 --region=us-west3
gcloud compute backend-services create web-backend-service \
--protocol=HTTP \
--port-name=http \
--health-checks=http-basic-check \
--global
gcloud compute backend-services add-backend web-backend-service \
--instance-group=lb-backend-group \
--instance-group-zone=us-west3-c \
--global
Create the fw-allow-health-check firewall rule.
gcloud compute firewall-rules create allow-tcp-rule-356 \
--network=default \
--action=allow \
--direction=ingress \
--target-tags=allow-health-check \
--rules=tcp:80
Now that the instances are up and running, set up a global static external IP
address that your customers use to reach your load balancer:
gcloud compute addresses create lb-ipv4-1 \
--ip-version=IPV4 \
--global
Create a health check for the load balancer:
gcloud compute health-checks create http http-basic-check \
--port 80
gcloud compute firewall-rules create www-firewall-network-lb \
--target-tags allow-health-check --allow tcp:80
------------------------------------
Configure the load balancing service
Create a static external IP address for your load balancer:
gcloud compute addresses create network-lb-ip-1 --region us-west3
Add a legacy HTTP health check resource:
gcloud compute http-health-checks create basic-check
Add a target pool in the same region as your instances. Run the following to create
the target pool and use the health check, which is required for the service to
function:
gcloud compute target-pools create www-pool --region us-west3 --http-health-check
basic-check
Add the instances to the pool:
gcloud compute target-pools add-instances www-pool --instances www1,www2,www3
Add a forwarding rule:
gcloud compute forwarding-rules create www-rule \
--region Region \
--ports 80 \
--address network-lb-ip-1 \
--target-pool www-pool
gcloud compute firewall-rules create www-firewall-network-lb \
--target-tags network-lb-tag --allow tcp:80