Showing posts with label cloud. Show all posts
Showing posts with label cloud. Show all posts

Friday, 6 March 2026

Complete beginner-friendly guide to deploy a React (UI) + Java (backend) app on Google Cloud Platform (GCP) and point your GoDaddy domain (mywebsite.com) so that when someone visits your site

 Below is a complete beginner-friendly guide to deploy a React (UI) + Java (backend) app on Google Cloud Platform (GCP) and point your GoDaddy domain (mywebsite.com) so that when someone visits your site, it loads from GCP.


Goal (what we’re building)

You already bought mywebsite.com on GoDaddy. You want:

  • React UI hosted on GCP

  • Java backend API hosted on GCP

  • Domain routing:

    • https://mywebsite.com → React UI

    • https://api.mywebsite.com → Java backend (recommended)

  • Secure HTTPS with Google-managed certificates

  • Production-ready and beginner-friendly

This guide uses Cloud Run (easiest modern way). It runs containers, scales automatically, and works great for Java.


What you need before starting

  1. A GCP account + billing enabled

  2. Your project created in GCP

  3. GoDaddy access (DNS settings)

  4. Installed tools on your machine:

    • Google Cloud SDK (gcloud)

    • Docker

    • Node.js (for React build)

    • Java + Maven/Gradle (for backend build)


Architecture options (choose one)

Option A (recommended): Cloud Run for backend + Cloud Storage/CDN for UI

  • UI is static (fast + cheap)

  • Backend is on Cloud Run

  • Best performance and standard setup

Option B: Cloud Run for both UI and backend

  • Simplest to understand (both are containers)

  • Slightly less optimized for static UI

I’ll explain Option A fully (best practice), and at the end I’ll include Option B quickly.


Part 1 — GCP project setup

1) Create/select a GCP project

In GCP Console:

  • Go to IAM & Admin → Manage resources

  • Create a project like: mywebsite-prod

2) Enable required APIs

Go to APIs & Services → Library and enable:

  • Cloud Run API

  • Artifact Registry API

  • Cloud Build API

  • Certificate Manager API (or “Cloud Managed Certificates” depending on UI)

  • Cloud DNS API (optional, not required if using GoDaddy DNS)

  • Cloud Storage API

  • (Optional but recommended) Cloud CDN, Load Balancing APIs


Part 2 — Deploy Java backend to Cloud Run

Cloud Run deploys containers, so we’ll containerize your Java backend.

3) Containerize your Java backend

In your Java backend project root, create a Dockerfile.

If you’re using Spring Boot (common)

# Build stage
FROM maven:3.9-eclipse-temurin-17 AS build
WORKDIR /app
COPY . .
RUN mvn -DskipTests package

# Run stage
FROM eclipse-temurin:17-jre
WORKDIR /app
COPY --from=build /app/target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","app.jar"]

Important: Cloud Run expects your app to listen on PORT (usually 8080), so in Spring Boot make sure it runs on 8080 (default is fine).


4) Create an Artifact Registry repo (once)

In Cloud Console:

  • Artifact Registry → Repositories → Create

  • Format: Docker

  • Name: mywebsite-repo

  • Region: pick one (ex: asia-south1 / us-central1)


5) Build and push image (easy way: Cloud Build)

Open terminal and run:

gcloud config set project YOUR_PROJECT_ID
gcloud auth login
gcloud auth configure-docker

Build + push using Cloud Build:

gcloud builds submit --tag REGION-docker.pkg.dev/YOUR_PROJECT_ID/mywebsite-repo/mybackend:1.0 .

Example:
us-central1-docker.pkg.dev/mywebsite-prod/mywebsite-repo/mybackend:1.0


6) Deploy backend to Cloud Run

gcloud run deploy mybackend \
--image REGION-docker.pkg.dev/YOUR_PROJECT_ID/mywebsite-repo/mybackend:1.0 \
--region REGION \
--platform managed \
--allow-unauthenticated

After deploy, Cloud Run gives you a URL like:
https://mybackend-xxxxx-uc.a.run.app

Test:

  • Open it in browser

  • Or call a health endpoint like /actuator/health


7) Configure CORS (important for React calling backend)

If your UI will be mywebsite.com and API will be api.mywebsite.com, allow that origin.

Spring example (conceptually):

  • Allow origin: https://mywebsite.com

  • Allow methods: GET/POST/PUT/DELETE/OPTIONS

This step depends on your Java framework. Do it now so browser requests don’t fail.


Part 3 — Deploy React UI (static hosting on GCP)

React is best hosted as static files.

8) Build your React app

Inside your React project:

npm install
npm run build

This produces a build/ folder.


9) Create a Cloud Storage bucket for website hosting

Go to Cloud Storage → Buckets → Create

  • Name: mywebsite-ui-bucket (must be globally unique)

  • Location: same region or multi-region

  • Public access: we will handle properly via LB/CDN (recommended), but for simplest beginner approach you can make it public.

Simple beginner approach (public bucket hosting)

In the bucket:

  • Upload contents of build/ (not the folder itself—upload files inside it)

  • Configure website:

    • index.html

    • 404.html (or index.html for SPA routing)

SPA routing tip: React apps need unknown routes to return index.html (so /about works). We’ll handle that better with Load Balancer later.


Part 4 — Connect domain in GoDaddy (DNS) to GCP

You want mywebsite.com to go to GCP.

To support HTTPS and clean routing, best practice is:

  • Put a Global HTTPS Load Balancer in front

  • Attach:

    • UI backend (Cloud Storage bucket)

    • API backend (Cloud Run service)

  • Then map your domain to the Load Balancer IP

This sounds scary, but it’s the most “real production” setup.


10) Create a Load Balancer (UI + API under one domain)

What we want the load balancer to do

  • Requests to mywebsite.com/* → Cloud Storage (React UI)

  • Requests to api.mywebsite.com/* → Cloud Run (Java backend)

  • Google-managed SSL certificates for both

Steps (high-level)

In GCP Console:

  1. Go to Network Services → Load balancing

  2. Create HTTP(S) Load Balancer

  3. Create Frontend

    • HTTPS

    • Add domains:

      • mywebsite.com

      • www.mywebsite.com

      • api.mywebsite.com

    • Request Google-managed certificate

  4. Create Backend

    • Backend 1: Cloud Storage bucket (UI)

    • Backend 2: Cloud Run service (API) using “Serverless NEG”

  5. URL Maps / Routing:

    • Host rule mywebsite.com → UI backend

    • Host rule www.mywebsite.com → UI backend

    • Host rule api.mywebsite.com → API backend

  6. Reserve a static external IP for the LB (recommended)

After creation, GCP gives you an IP like: 34.xxx.xxx.xxx


11) Update GoDaddy DNS

Now go to GoDaddy → Domain → DNS

Add/Update records:

Root domain (mywebsite.com)

GoDaddy often supports an A record:

  • Type: A

  • Name: @

  • Value: <Load Balancer IP>

  • TTL: default

www subdomain (www.mywebsite.com)

  • Type: CNAME

  • Name: www

  • Value: mywebsite.com

API subdomain (api.mywebsite.com)

If using same LB IP (recommended with host-based routing):

  • Type: A

  • Name: api

  • Value: <Load Balancer IP>


12) Wait for DNS + SSL to become active

DNS can take minutes to hours to propagate.
SSL certificate provisioning may take some time too (commonly 15–60 minutes, sometimes longer).

Once active:

  • https://mywebsite.com loads React

  • https://api.mywebsite.com hits your backend


Part 5 — Connect React UI to Java API

13) Use environment variables in React

In React, create .env.production:

REACT_APP_API_BASE_URL=https://api.mywebsite.com

Then in code:

const API = process.env.REACT_APP_API_BASE_URL;
fetch(`${API}/your-endpoint`)

Rebuild:

npm run build

Re-upload build files to the bucket.


Part 6 — Recommended production improvements

14) Enable Cloud CDN for UI

If you front the bucket with Load Balancer, you can enable Cloud CDN for fast global caching.

15) Add backend environment config securely

Use Cloud Run environment variables:

  • DB connection string

  • secrets (prefer Secret Manager)

16) Logging + monitoring

Cloud Run logs automatically appear in:

  • Cloud Logging

  • Cloud Monitoring


Common beginner mistakes (and fixes)

1) React routes return 404

Fix: configure LB / bucket website to serve index.html for unknown paths (SPA fallback). The Load Balancer URL map can do this cleanly.

2) CORS errors

Fix: allow origin https://mywebsite.com in Java backend.

3) Backend works by URL but not by custom domain

Fix: ensure:

  • api.mywebsite.com DNS points to LB IP

  • LB host rule routes api.mywebsite.com to Cloud Run backend

  • SSL cert includes api.mywebsite.com

4) SSL stuck in “Provisioning”

Fix checklist:

  • DNS must already point correctly to LB IP

  • No conflicting records

  • Wait a bit; if still stuck, re-check domain ownership / DNS


Option B (simpler): Host both React and Java on Cloud Run

If you don’t want load balancers/buckets yet:

  • Make a single backend that serves React build too (Java serves static files)

  • Or deploy React separately as a container on Cloud Run

But: mapping a custom domain directly to Cloud Run is possible; however routing mywebsite.com and api.mywebsite.com becomes slightly less flexible than the LB approach.

end-to-end guide to host your React UI + Java backend on AWS and point mywebsite.com to AWS so visitors load your site from AWS

 Below is a beginner-friendly, end-to-end guide to host your React UI + Java backend on AWS and point mywebsite.com to AWS so visitors load your site from AWS.

I’ll use a setup that’s popular, low-cost, and easy to maintain:

  • React (UI)Amazon S3 + CloudFront (CDN)

  • Java (Backend API)AWS Elastic Beanstalk (runs your Spring Boot/JAR or WAR with minimal ops)

  • Domain + HTTPSRoute 53 + ACM certificates

  • Optional (recommended): mywebsite.com for UI, api.mywebsite.com for backend API


1) What you’re building (simple architecture)

When a user opens mywebsite.com:

  1. CloudFront serves your React static files globally (fast + HTTPS).

  2. React calls your backend at api.mywebsite.com.

  3. Elastic Beanstalk runs your Java app behind a load balancer.

This is a clean separation and avoids mixing static hosting with server APIs.


2) Prerequisites

  • An AWS account

  • Your domain: mywebsite.com (registered anywhere is fine)

  • React project builds correctly locally (npm run build)

  • Java backend packaged (commonly Spring Boot JAR)


3) Deploy the React UI to S3 + CloudFront

Step 3.1 — Build your React app

From your React project folder:

npm install
npm run build

This creates a build/ directory (or dist/ depending on your toolchain).

Step 3.2 — Create an S3 bucket for hosting

In AWS Console → S3 → Create bucket:

  • Bucket name: something like mywebsite-ui-prod-<unique>

  • Region: choose one (any is fine)

  • Block all public access: keep it ON (recommended)

Why keep it private? Because CloudFront can securely access it while the bucket stays private.

Step 3.3 — Upload the build output to S3

You can upload via Console or CLI.

CLI method (recommended):

aws s3 sync build/ s3://YOUR_BUCKET_NAME --delete

Step 3.4 — Create a CloudFront distribution in front of S3

AWS Console → CloudFront → Create distribution:

  • Origin domain: your S3 bucket

  • Origin access: choose Origin Access Control (OAC) (recommended) and let AWS update bucket policy

  • Default root object: index.html

Important for React SPA routing: configure CloudFront to return index.html for unknown paths (so /about works). AWS provides a prescriptive pattern for React SPA on S3 + CloudFront.


4) Deploy the Java backend to Elastic Beanstalk

Elastic Beanstalk is beginner-friendly for Java: you upload your app, and it provisions EC2 + load balancer + scaling.

Step 4.1 — Package your backend

For Spring Boot (Maven), typically:

mvn clean package

You’ll get something like:

  • target/myapp.jar

Elastic Beanstalk’s Java SE platform can run compiled JAR apps directly.

Step 4.2 — Create an Elastic Beanstalk application

AWS Console → Elastic Beanstalk → Create application:

  • Environment: Web server environment

  • Platform: Java

  • Upload your application code (your JAR/WAR)

  • Choose a sample instance type (e.g., t3/t4g small) for dev

After creation, Elastic Beanstalk will give you a URL like:
http://your-env.eba-xyz.region.elasticbeanstalk.com

Step 4.3 — Check your API works

Test:

  • https://your-env.../health or any endpoint you expose

Step 4.4 — CORS (don’t skip)

If your UI runs on https://mywebsite.com and API on https://api.mywebsite.com, you must allow CORS in your backend.

For Spring Boot, configure CORS to allow your frontend domain.


5) Add HTTPS (SSL) certificates with ACM

You’ll want HTTPS on both:

  • mywebsite.com (CloudFront)

  • api.mywebsite.com (Load balancer / EB)

Step 5.1 — Certificate for CloudFront must be in us-east-1

For CloudFront, AWS requires the ACM certificate to be requested/imported in US East (N. Virginia) us-east-1.

So:
AWS Console → Certificate Manager (ACM) → switch region to us-east-1 → Request certificate for:

  • mywebsite.com

  • www.mywebsite.com (optional but common)

Use DNS validation.

Step 5.2 — Certificate for the backend (Elastic Beanstalk LB)

For the backend load balancer, you can request the certificate in the same region where your Elastic Beanstalk environment is running (not necessarily us-east-1). CloudFront’s us-east-1 rule is the special case.

Then attach that cert to the load balancer listener (HTTPS 443). Elastic Beanstalk can manage ALB listeners via configuration, or you can adjust in EC2 Load Balancers depending on how your environment is set up.


6) Point your domain (mywebsite.com) to AWS

You have two common situations:

Option A (easiest): Use Route 53 as your DNS provider

  1. Route 53 → Hosted zones → create hosted zone for mywebsite.com

  2. Update nameservers at your domain registrar to Route 53 NS records

Then create records:

For the UI

Create an A (Alias) record:

  • Name: mywebsite.com

  • Alias to: your CloudFront distribution

Route 53 alias records are the AWS-native way to route apex domains to CloudFront.

(Optional) also:

  • www.mywebsite.com → Alias to same CloudFront distribution

For the API

Create:

  • api.mywebsite.com → Alias/CNAME to the Elastic Beanstalk load balancer DNS name (or EB CNAME)

Option B: Keep DNS at your current provider

If you don’t want Route 53, create DNS records where your DNS is hosted:

  • For UI: point www to CloudFront using CNAME (easy)

  • For apex mywebsite.com: many DNS providers support ALIAS/ANAME at apex. If not, moving DNS to Route 53 is usually simplest.


7) Make the React app call the right backend

Recommended:

  • UI: https://mywebsite.com

  • API: https://api.mywebsite.com

In React, set an environment variable:

.env.production

REACT_APP_API_BASE_URL=https://api.mywebsite.com

Build and redeploy UI after changes.


8) Production checklist (quick but important)

  • CloudFront SPA routing is configured (unknown routes → index.html)

  • HTTPS works on mywebsite.com (ACM cert in us-east-1)

  • Route 53 alias to CloudFront for apex domain

  • Backend has CORS allowing https://mywebsite.com

  • Backend uses HTTPS and you redirect HTTP→HTTPS

  • Add monitoring:

    • CloudWatch logs (EB)

    • CloudFront access logs (optional)


9) Simple CI/CD idea (optional)

Once the manual flow works, automate:

  • UI:

    • GitHub Actions: build → aws s3 sync → CloudFront invalidation

  • Backend:

    • Elastic Beanstalk: deploy new JAR on push (EB CLI or GitHub Actions)


Common beginner mistakes (and fixes)

  1. CloudFront + SSL not working for your domain

    • You likely created the ACM cert in the wrong region.

    • For CloudFront it must be us-east-1

  2. React refresh on /some-route gives 403/404

    • You need SPA routing behavior (serve index.html)

  3. UI can’t call API (CORS error)

    • Fix backend CORS config to allow your UI domain.

Configure an AWS Application Load Balancer for a Spring Boot App (Step-by-Step)

 Below is a step-by-step, “article-style” guide to configure an AWS Load Balancer for a new Spring Boot application. I’ll show a clean, production-friendly setup using Application Load Balancer (ALB) (best fit for HTTP/HTTPS, path-based routing, host-based routing, WebSockets, etc.). I’ll include both EC2 + Auto Scaling and ECS/Fargate notes where it matters.


Configure an AWS Application Load Balancer for a Spring Boot App (Step-by-Step)

What you’re building

A typical secure AWS setup looks like this:

Internet → ALB (HTTP/HTTPS) → Target Group → Spring Boot instances/containers

The load balancer:

  • Terminates TLS (HTTPS)

  • Health-checks your app

  • Distributes traffic across instances

  • Supports scaling and zero-downtime deployments (with the right strategy)


Prerequisites

Before creating the load balancer, decide these basics:

  1. Where is Spring Boot running?

    • EC2 instances (common)

    • ECS/Fargate (common)

    • EKS (then you’ll likely use AWS Load Balancer Controller; similar concepts)

  2. App port

    • Common: 8080 (Spring Boot default)

    • We’ll assume 8080

  3. Health endpoint

    • Best practice: /actuator/health (Spring Boot Actuator)

    • Use the “liveness” style endpoint for ALB checks where possible


Step 1: Prepare the Spring Boot app for ALB health checks

Enable actuator (recommended)

In build.gradle / pom.xml, include actuator.

Then configure:

  • Expose health endpoint

  • Ensure it returns 200 OK

Example application.yml:

management:
endpoints:
web:
exposure:
include: health,info
endpoint:
health:
probes:
enabled: true

Recommended health paths:

  • /actuator/health (simple)

  • /actuator/health/liveness (even better for ALB checks)

Tip: ALB health checks must succeed quickly—avoid slow DB checks on the main health check path unless you specifically want that behavior.


Step 2: Network foundation (VPC + subnets)

For an internet-facing ALB, you want:

  • VPC

  • 2+ public subnets in different AZs (ALB requirement for HA)

  • Route table for public subnets with route to an Internet Gateway

Also ensure your backend compute (EC2/ECS tasks) is in:

  • private subnets (recommended), OR

  • public subnets (simpler but less ideal)


Step 3: Create / confirm Security Groups

You’ll typically use two security groups:

A) ALB Security Group (inbound from the internet)

Inbound rules:

  • HTTP 80 from 0.0.0.0/0 (optional; often used only to redirect to HTTPS)

  • HTTPS 443 from 0.0.0.0/0 (recommended for production)

Outbound:

  • Allow all (default is fine), or restrict to backend security group ports.

B) Application Security Group (inbound only from ALB)

Inbound rules:

  • Custom TCP 8080 source = ALB security group

  • SSH 22 only from your VPN/bastion/office IP (if EC2; avoid opening to world)

This is the key security pattern: instances accept app traffic only from the ALB.


Step 4: Create a Target Group

Go to EC2 → Target Groups → Create target group

Choose:

  • Target type

    • Instance (if EC2)

    • IP (if ECS/Fargate, or if you want to register IPs)

    • Lambda (rare for Spring Boot directly)

Configuration:

  • Protocol: HTTP

  • Port: 8080

  • VPC: your VPC

Health checks:

  • Protocol: HTTP

  • Path: /actuator/health (or /actuator/health/liveness)

  • Healthy threshold: 2–3

  • Unhealthy threshold: 2–3

  • Timeout: 5s

  • Interval: 15–30s

  • Success codes: 200 (or 200-399 depending on your endpoint)

Pro tip: Start with /actuator/health and 200-399 if you have redirects or special behavior.

Register targets:

  • If EC2: select instances and add them (or let Auto Scaling do it later)

  • If ECS: ECS service will attach tasks automatically


Step 5: Create the Application Load Balancer (ALB)

Go to EC2 → Load Balancers → Create Load Balancer → Application Load Balancer

  1. Name it (e.g., springboot-alb-prod)

  2. Scheme: Internet-facing (or internal if private)

  3. IP address type: IPv4 (or dualstack if needed)

  4. Network mapping:

    • Select your VPC

    • Select at least two public subnets across AZs

  5. Security group: attach the ALB SG you created


Step 6: Configure ALB Listeners and Rules

Option A (common): HTTP redirects to HTTPS + HTTPS forwards to target group

Listener 80 (HTTP):

  • Action: Redirect to HTTPS 443

Listener 443 (HTTPS):

  • Attach an ACM certificate

  • Forward to your target group

Add TLS Certificate (ACM)

Go to AWS Certificate Manager (ACM):

  • Request a public certificate for app.yourdomain.com

  • Validate via DNS (recommended)

  • Once “Issued”, select it in the ALB 443 listener


Step 7: Connect ALB to your Spring Boot compute

If using EC2 + Auto Scaling (recommended for reliability)

  1. Put your EC2 instances into an Auto Scaling Group

  2. In the ASG, attach the Target Group

  3. Ensure instances use Application SG and are in correct subnets

  4. Confirm your app runs on 8080 and is reachable from ALB SG

If using ECS/Fargate

  1. Create/update ECS Service

  2. Enable Load balancing

  3. Choose the ALB, listener, and target group

  4. Ensure task security group allows 8080 inbound from ALB SG

  5. Confirm container port mapping exposes 8080


Step 8: Configure DNS (Route 53)

If you own the domain in Route 53:

Route 53 → Hosted zone → Create record:

  • Record name: app (for app.yourdomain.com)

  • Type: A (Alias)

  • Alias to: your ALB DNS name

Now your public URL points to the ALB.


Step 9: Validate end-to-end

  1. Open the ALB DNS name:

    • http://<alb-dns> (should redirect to HTTPS)

    • https://<alb-dns> (should show your app)

  2. Check target group health:

    • Targets should be healthy

  3. Check logs if unhealthy:

    • Security group rules (most common issue)

    • Health check path/port wrong

    • App not listening on 0.0.0.0 / port mismatch


Step 10: Production-grade hardening (highly recommended)

Enable access logs

ALB → Attributes → Access logs → store in S3
Great for debugging and audit.

Enable deletion protection (prod)

Prevents accidental deletion.

Stickiness (only if needed)

If your app uses in-memory sessions (not ideal), enable stickiness. Better: use stateless JWT or external session store.

Timeouts

Tune:

  • Idle timeout (default 60s)
    Useful for long requests or SSE/WebSockets patterns.

Use WAF (for internet-facing apps)

Attach AWS WAF to ALB:

  • Managed rule groups

  • Rate limiting

  • IP reputation filters

Use HTTPS-only

Disable HTTP listener or always redirect HTTP → HTTPS.


Common Spring Boot + ALB gotchas (and fixes)

  1. Health check failing

    • Fix path (/actuator/health)

    • Confirm actuator exposure

    • Confirm security group allows ALB → app port

  2. Wrong port

    • ALB forwards to 8080, but app actually runs on 80 or 5000

    • Align target group port + runtime port

  3. App binds to localhost

    • Ensure server binds to 0.0.0.0 (typical in containers)

    • Spring Boot default is usually fine on EC2

  4. TLS at ALB + app thinks it’s HTTP

    • Add forwarded headers support:

      • For modern Spring Boot, set:

        server.forward-headers-strategy=framework
    • Helps with redirects, scheme detection, secure cookies.


Quick reference: minimal checklist

  • ALB in 2 public subnets

  • ALB SG allows 443 from internet

  • App SG allows 8080 from ALB SG

  • Target group port 8080, correct health path

  • Listener 443 forwards to target group

  • ACM cert attached + Route 53 alias record

  • Targets show healthy


If you tell me EC2 vs ECS/Fargate, your domain setup (Route53 or external), and whether you want blue/green deployments, I can tailor this into an even more “copy/paste runnable” runbook (including exact security group rules, recommended health endpoints, and deployment strategy).

Step-by-step: Configure a Google Cloud Load Balancer for a new Spring Boot app (GCP)

 This walkthrough shows a solid, production-style setup for a Spring Boot application running on Google Cloud Platform, fronted by a Google Cloud HTTP(S) Load Balancer with TLS, health checks, autoscaling, and clean routing.

I’ll cover two common deployment paths:

  • Path A (recommended for many Spring Boot teams): Compute Engine Managed Instance Group (MIG) + External HTTP(S) Load Balancer

  • Path B (container-first): GKE / Cloud Run (quick notes at the end)


What you’ll build

Users → Global external HTTP(S) Load Balancer → Backend service → MIG (Spring Boot VMs)

Key pieces:

  • A Spring Boot service listening on a known port (e.g., 8080)

  • A health endpoint that returns 200 OK (e.g., /actuator/health)

  • A Managed Instance Group (for scale + self-heal)

  • A Backend service with a health check

  • A URL map + target proxy + forwarding rule

  • Optional: Managed SSL certificate + Cloud DNS


Prereqs

  • A GCP project with billing enabled

  • gcloud installed and authenticated

  • A domain name (optional but recommended for HTTPS with managed cert)

  • Spring Boot app ready to run in production profile

Set your defaults:

gcloud config set project YOUR_PROJECT_ID
gcloud config set compute/region asia-south1
gcloud config set compute/zone asia-south1-a

Step 1: Prepare your Spring Boot app for load balancing

1.1 Add a health endpoint

If you use Spring Actuator:

Gradle

implementation 'org.springframework.boot:spring-boot-starter-actuator'

application.yml

management:
endpoints:
web:
exposure:
include: health,info
endpoint:
health:
probes:
enabled: true

Health endpoint:

  • /actuator/health (or /actuator/health/liveness depending on config)

1.2 Make sure your app binds correctly

Ensure Spring Boot binds to all interfaces:

server:
address: 0.0.0.0
port: 8080

1.3 Keep it stateless

A load balancer will route requests across instances. Prefer:

  • external session store (Redis / Cloud Memorystore), or

  • JWT/stateless auth


Step 2: Build a VM image that runs your Spring Boot app

You have two practical approaches:

Option A: Startup script on a base OS (simple)

  • Create an instance template that installs Java and runs the jar via a startup script.

Option B: Bake a custom image (cleaner, faster scale-up)

  • Use Packer or custom image pipeline.

Below is Option A (fast to implement).


Step 3: Create an instance template (with startup script)

3.1 Upload your app artifact

Example: put the jar in a GCS bucket:

gsutil mb -l asia-south1 gs://YOUR_BUCKET_NAME
gsutil cp build/libs/your-app.jar gs://YOUR_BUCKET_NAME/

3.2 Create a service account for instances (recommended)

gcloud iam service-accounts create springboot-vm-sa \
--display-name="Spring Boot VM Service Account"

Grant only what you need (example: read jar from GCS):

gcloud projects add-iam-policy-binding YOUR_PROJECT_ID \
--member="serviceAccount:springboot-vm-sa@YOUR_PROJECT_ID.iam.gserviceaccount.com" \
--role="roles/storage.objectViewer"

3.3 Create a startup script

Create startup.sh locally:

cat > startup.sh <<'EOF'
#!/bin/bash
set -e

APP_BUCKET="YOUR_BUCKET_NAME"
APP_JAR="your-app.jar"
APP_DIR="/opt/app"
PORT="8080"

apt-get update
apt-get install -y default-jre-headless google-cloud-cli

mkdir -p ${APP_DIR}
gsutil cp gs://${APP_BUCKET}/${APP_JAR} ${APP_DIR}/${APP_JAR}

cat > /etc/systemd/system/springboot.service <<SYSTEMD
[Unit]
Description=Spring Boot App
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=${APP_DIR}
ExecStart=/usr/bin/java -jar ${APP_DIR}/${APP_JAR} --server.port=${PORT}
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
SYSTEMD

systemctl daemon-reload
systemctl enable springboot.service
systemctl start springboot.service
EOF

3.4 Create the instance template

gcloud compute instance-templates create springboot-template \
--machine-type=e2-medium \
--service-account=springboot-vm-sa@YOUR_PROJECT_ID.iam.gserviceaccount.com \
--scopes=https://www.googleapis.com/auth/cloud-platform \
--tags=springboot-backend \
--metadata-from-file=startup-script=startup.sh \
--image-family=debian-12 \
--image-project=debian-cloud

Step 4: Create a Managed Instance Group (MIG)

gcloud compute instance-groups managed create springboot-mig \
--base-instance-name=springboot \
--size=2 \
--template=springboot-template

Enable autoscaling (example):

gcloud compute instance-groups managed set-autoscaling springboot-mig \
--max-num-replicas=10 \
--min-num-replicas=2 \
--target-cpu-utilization=0.6 \
--cool-down-period=60

Step 5: Allow traffic from the load balancer to your instances (Firewall)

For an external HTTP(S) Load Balancer, backend VMs must allow traffic from Google LB health check + proxy ranges.

Create a firewall rule allowing traffic to port 8080 from Google LB ranges:

gcloud compute firewall-rules create allow-lb-to-springboot \
--network=default \
--action=ALLOW \
--direction=INGRESS \
--rules=tcp:8080 \
--source-ranges=130.211.0.0/22,35.191.0.0/16 \
--target-tags=springboot-backend

If you use a separate health check path, same port is fine.


Step 6: Create a health check for the backend

Use HTTP health check to /actuator/health:

gcloud compute health-checks create http springboot-hc \
--port 8080 \
--request-path /actuator/health \
--check-interval 10s \
--timeout 5s \
--unhealthy-threshold 3 \
--healthy-threshold 2

Step 7: Create a backend service and attach the MIG

7.1 Create backend service

gcloud compute backend-services create springboot-backend \
--protocol=HTTP \
--port-name=http \
--health-checks=springboot-hc \
--global

7.2 Attach the MIG

First, make the MIG a backend (needs an instance group reference; MIG is zonal by default):

gcloud compute backend-services add-backend springboot-backend \
--instance-group=springboot-mig \
--instance-group-zone=asia-south1-a \
--global

Step 8: Create URL map (routing rules)

Basic single-service routing:

gcloud compute url-maps create springboot-urlmap \
--default-service springboot-backend

If later you want /api/* to one backend and /static/* to another, you’d add path matchers.


Step 9: Create the target HTTP proxy + forwarding rule (HTTP)

9.1 Target HTTP proxy

gcloud compute target-http-proxies create springboot-http-proxy \
--url-map=springboot-urlmap

9.2 Global forwarding rule (port 80)

gcloud compute forwarding-rules create springboot-http-fr \
--global \
--target-http-proxy=springboot-http-proxy \
--ports=80

Get the LB IP:

gcloud compute forwarding-rules describe springboot-http-fr --global --format="value(IPAddress)"

Test:

curl -i http://LB_IP/
curl -i http://LB_IP/actuator/health

At this point you have a working HTTP load balancer.


Step 10: Enable HTTPS with a managed certificate (recommended)

10.1 Reserve a static global IP (best practice)

gcloud compute addresses create springboot-lb-ip --global
gcloud compute addresses describe springboot-lb-ip --global --format="value(address)"

Re-create the forwarding rule to use this IP (or create a new one):

gcloud compute forwarding-rules delete springboot-http-fr --global -q

gcloud compute forwarding-rules create springboot-http-fr \
--global \
--address=springboot-lb-ip \
--target-http-proxy=springboot-http-proxy \
--ports=80

10.2 Create a managed SSL certificate

gcloud compute ssl-certificates create springboot-managed-cert \
--domains=yourdomain.com \
--global

Managed cert becomes ACTIVE only after DNS points to the LB IP.

10.3 Create an HTTPS target proxy

gcloud compute target-https-proxies create springboot-https-proxy \
--url-map=springboot-urlmap \
--ssl-certificates=springboot-managed-cert

10.4 Create HTTPS forwarding rule (port 443)

gcloud compute forwarding-rules create springboot-https-fr \
--global \
--address=springboot-lb-ip \
--target-https-proxy=springboot-https-proxy \
--ports=443

Step 11: Point DNS to the load balancer

In your DNS provider (or Cloud DNS), create:

  • A record: yourdomain.comLB_STATIC_IP

Once propagated, check cert status:

gcloud compute ssl-certificates describe springboot-managed-cert --global

When it’s ACTIVE:

curl -i https://yourdomain.com/actuator/health

Step 12: (Strongly recommended) Force HTTP → HTTPS redirect

Create a second URL map just for redirects:

gcloud compute url-maps create springboot-redirect-map \
--default-url-redirect=httpsRedirect=true,responseCode=301

Create a redirect proxy and update the HTTP forwarding rule:

gcloud compute target-http-proxies create springboot-redirect-proxy \
--url-map=springboot-redirect-map

gcloud compute forwarding-rules delete springboot-http-fr --global -q

gcloud compute forwarding-rules create springboot-http-fr \
--global \
--address=springboot-lb-ip \
--target-http-proxy=springboot-redirect-proxy \
--ports=80

Now all http:// gets redirected to https://.


Step 13: Observability & operations checklist

Logging and metrics

  • Enable Cloud Logging and Cloud Monitoring (default on GCE)

  • Add Spring Boot structured logs (JSON) if you can

  • Consider exporting app metrics using Micrometer to Cloud Monitoring or Prometheus (if on GKE)

Security hardening

  • Put instances in private subnets (if using Shared VPC) and only allow LB ingress

  • Use least privilege for instance service account

  • Use Secret Manager for secrets (don’t bake into VM)

Reliability

  • Use regional MIG for higher availability across zones (recommended for prod)

  • Enable autohealing on MIG using the same health check:

gcloud compute instance-groups managed set-autohealing springboot-mig \
--health-check=springboot-hc \
--initial-delay=120

Common Spring Boot gotchas behind a load balancer

  • If you generate absolute URLs or redirects, configure forwarded headers:

    • In Spring Boot, ensure it respects X-Forwarded-* headers (depends on version and config).

  • If you have large uploads, tune max request size and timeouts.

  • Health endpoint must be fast and consistently return 200.


Alternative: If your Spring Boot app is containerized

Cloud Run

  • Easiest: deploy to Cloud Run and optionally put it behind an external HTTPS LB for custom domains / advanced routing / WAF.

  • Cloud Run already scales and handles many LB-ish concerns.

GKE Ingress

  • You’d create a Kubernetes Service + Ingress (or Gateway API), and GKE provisions the LB.

If you tell me which runtime you’re actually using (GCE VM, GKE, or Cloud Run) and whether you need internal or external LB, I’ll tailor the article to that exact architecture and include the right commands and diagrams.