Google Cloud Platform (GCP): Configuring Reverse Proxy and Load Balancing for Backend and Frontend Routing
Let's Create a VPC
VM for Load Balancer, Frontend, Backend, DB
Let's create VM from LB and access it with SSH end External IP
sudo apt update -y
sudo apt install nginx -y
Create Cloud Nat and Router
Create VM Instance for Frontend and install Node.JS
Install a React app in Frontend VM
Accessing Frontend from LB
cd /etc/nginx
vim nginx.conf
And Replace with these lines
events {
# empty placeholder
}
http {
server {
listen 80;
location / {
proxy_pass http://frontend;
}
}
upstream frontend {
server 192.168.0.4:80;
}
}
You can test nginx connection with
root@vm-instance-lb:/etc/nginx# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Next reload the nginx server
nginx -s reload
Now if we go to load balancer's public IP
Now Let's Create Two VM for Backend "vm-instance-backend-1 and vm-instance-backend-2"
sudo apt update -y
sudo su
curl -fsSL https://deb.nodesource.com/setup_18.x | bash - &&\
apt-get install -y nodejs
corepack enable
mkdir be1
cd b1
npm init -v
yarn add express
Barebone Express js code
// Import required modules
const express = require('express');
// Create an instance of an Express application
const app = express();
// Define a port number
const PORT = 80;
// Create a route for the root path
app.get('/', (req, res) => {
res.send('Hello from BE 1!');
});
// Start the server and listen on the specified port
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
So let's edit index.js file from Backend1 and Backend2 with the express code
Now let's update the nginx conf with
events {
# empty placeholder
}
http {
server {
listen 80;
location / {
proxy_pass http://frontend;
}
location /api/ {
rewrite ^/api/(.*)$ /$1 break;
proxy_pass http://backend;
}
}
upstream frontend {
server 192.168.0.4:80;
}
upstream backend {
server 192.168.0.5;
server 192.168.0.6;
}
}
Here 192.168.0.5 and 192.168.0.6 is BE's internal IP
nginx -t
nginx -s reload
Now if we go http://34.66.211.228/api/ it will show responses from BE1 and BE2 with round-robin algorithom