How to Create a Cluster of NGINX web server with an Instance Group
There may be some scenarios in which you need your NGINX web server to be completely infallible. Unfortunately, there’s no such thing as an unbreakable server. However, you can queue up multiple web servers to use as backups in the event your primary server fails.
You need to use Instance Templates on the Cloud Compute Engine to launch multiple Linux VMs at one time. Then, you need to configure a series of Network Load Balancers to spread traffic evenly across the servers.
Step 1 - Launch Google Cloud Console and log in.
Step 2 - Launch a new startup script and call it the following: nginx-startup.txt. Type in this command to launch the script:
#!/bin/bash apt-get update apt-get install -y nginx service nginx start
Step 3 - Select the option to Create a new Instance Template. Enter the following command to launch it:
gcloud compute instance-templates create nginx-template \ --metadata-from-file startup-script=nginx-startup.txt
Step 4 - Now, set up a new target pool by typing in the following command:
gcloud compute target-pools create nginx-pool
Step 5 - Run the following command to create an Instance Group
gcloud compute instance-groups managed create nginx-group \ --base-instance-name nginx \ --size 2 \ --template nginx-template \ --target-pool nginx-pool
Step 5 - Return to the Google Cloud Console and navigate to the VM list where you should see two new entries. These are the VMs you’ve just established.
Step 6 - Set up a regional network load balancing rule for the machines you’ve just launched. You can set up the same rule for multiple machines by typing in the following command:
gcloud compute forwarding-rules create nginx-lb \ --ports 80 \ --target-pool nginx-pool
Step 7 - When asked to input a region, select the most appropriate option for your location (e.g. us-central1).
Step 8 - Input the following command to enable HTTP authentication for all the VMs in your Instance Template:
gcloud compute firewall-rules create allow-80 --allow tcp:80
Step 9 - Now your regional load balancer is activated, find out the new IP address assigned to your VMs. The quickest way to do this is to run this command:
gcloud compute forwarding-rules list
Step 10 - Highlight the IP address to copy it to the clipboard.
Step 11 - Open your browser. Press Ctrl+V to paste the IP address into the search box.
Using Instance Templates is a smart way to set up multiple VMs with identical configurations. The use of a load balancing rule is especially helpful because it spreads traffic across several machines. If one develops a problem and becomes unusable, its traffic is automatically reassigned to the remaining VMs.