Skip to main content

Protecting Web Applications with Cloud Armor

Configure Cloud Armor security policies with rate limiting and preconfigured WAF rules to block floods and SQL injection at the edge.

38 Terms

Overview and What You Will Learn

Cloud Armor is Google Cloud's web application firewall (WAF) and DDoS protection service, and it evaluates each request against a security policy at the load balancer before the request reaches your backend. In this lab you will build a small external load balancer, add a preconfigured SQL injection rule and a rate-limiting rule, test the SQL injection rule in preview mode, enforce it, and confirm the results with real requests.

  • Building a minimal global external Application Load Balancer
  • Creating a security policy with ordered rules
  • Adding a preconfigured SQL injection rule in preview mode
  • Adding a per-IP rate-limiting rule
  • Enforcing rules and reading Cloud Armor logs

Why This Matters in Production

Rate limiting at the edge keeps a flood from consuming the compute that real customers need. Picture a public API at a company like Hotstar during a major match: one source sending thousands of valid-looking requests per minute can exhaust backend capacity even though no single request is malicious. A Cloud Armor rate-based rule stops that pattern before it touches the backend, and a preconfigured WAF rule blocks known injection attacks at the same point.

Core Principles

A Cloud Armor policy is an ordered list of rules. Each rule has a priority number, a match expression and an action. The lowest number is evaluated first, the first matching rule decides the outcome, and a default rule at priority 2147483647 handles everything else.

flowchart TD A([Client request]) --> B[Load balancer] B --> C[Cloud Armor policy] C -->|deny or ban| D[403 or 429 response] C -->|allow| E[(Backend service)] classDef user fill:#DBEAFE,color:#1E293B classDef tool fill:#326CE5,color:#FFFFFF classDef block fill:#EF4444,color:#FFFFFF classDef ok fill:#10B981,color:#FFFFFF class A user class B,C tool class D block class E ok

Two rule types do most of the work. Rate-based rules limit how many requests one client key, such as an IP address, can send in an interval. Preconfigured WAF rules are maintained by Google and match known attack signatures such as SQL injection and cross-site scripting.

Remember

A rate-based rule that matches every request and allows conforming traffic ends evaluation for all of those requests. Put specific deny rules at lower priority numbers than a catch-all rate rule, or they will never run.

Detailed Step-by-Step Practical Lab

  1. Create the project and link billing:
Bash
gcloud projects create mumbai-armor-lab-2026 --name="Cloud Armor Lab"
gcloud billing projects link mumbai-armor-lab-2026 \
--billing-account=0A1B2C-3D4E5F-6A7B8C
gcloud config set project mumbai-armor-lab-2026
gcloud services enable compute.googleapis.com logging.googleapis.com
  1. Build a minimal global external Application Load Balancer. The backend has no VMs attached, so allowed requests return a 5xx error. That is fine here, because Cloud Armor acts before the backend is reached:
Bash
gcloud compute addresses create armor-lab-ip --global
gcloud compute health-checks create http health-check-armor --port=80
gcloud compute backend-services create backend-armor-lab \
--protocol=HTTP --port-name=http \
--health-checks=health-check-armor \
--load-balancing-scheme=EXTERNAL_MANAGED \
--global
gcloud compute url-maps create armor-lab-map \
--default-service=backend-armor-lab
gcloud compute target-http-proxies create armor-lab-proxy \
--url-map=armor-lab-map
gcloud compute forwarding-rules create armor-lab-fr \
--load-balancing-scheme=EXTERNAL_MANAGED \
--network-tier=PREMIUM \
--address=armor-lab-ip \
--global \
--target-http-proxy=armor-lab-proxy \
--ports=80
  1. Create the security policy:
Bash
gcloud compute security-policies create armor-policy-lab \
--description="SQL injection and rate limiting for the lab backend"
  1. Add the preconfigured SQL injection rule at priority 1000, in preview mode first. Preview logs what the rule would block without blocking anything:
Bash
gcloud compute security-policies rules create 1000 \
--security-policy=armor-policy-lab \
--expression="evaluatePreconfiguredExpr('sqli-v33-stable')" \
--action=deny-403 \
--preview
  1. Add the rate-limiting rule at priority 2000. A client IP above 100 requests per minute receives HTTP 429, and a client above 300 requests per minute is banned for 5 minutes. It comes after the SQL injection rule so attack requests are checked first:
Bash
gcloud compute security-policies rules create 2000 \
--security-policy=armor-policy-lab \
--expression="true" \
--action=rate-based-ban \
--rate-limit-threshold-count=100 \
--rate-limit-threshold-interval-sec=60 \
--ban-threshold-count=300 \
--ban-threshold-interval-sec=60 \
--ban-duration-sec=300 \
--conform-action=allow \
--exceed-action=deny-429 \
--enforce-on-key=ip
  1. Attach the policy to the backend service, turn on request logging, and review the rules:
Bash
gcloud compute backend-services update backend-armor-lab \
--security-policy=armor-policy-lab \
--enable-logging --logging-sample-rate=1.0 \
--global
gcloud compute security-policies rules list \
--security-policy=armor-policy-lab
  1. Wait a few minutes for the load balancer to propagate, then send a normal request and a SQL injection attempt. While rule 1000 is in preview, both reach the backend and return the same 5xx status:
Bash
LB_IP=$(gcloud compute addresses describe armor-lab-ip --global \
--format="value(address)")
curl -s -o /dev/null -w "%{http_code}\n" "http://$LB_IP/"
curl -s -o /dev/null -w "%{http_code}\n" "http://$LB_IP/?id=1%27%20OR%20%271%27%3D%271"
  1. Check the logs to see what the preview rule would have blocked:
Bash
gcloud logging read \
'jsonPayload.previewSecurityPolicy.name="armor-policy-lab"' \
--limit=5 --freshness=30m
  1. Enforce the SQL injection rule, wait about a minute, and repeat the attack request. It should now return 403:
Bash
gcloud compute security-policies rules update 1000 \
--security-policy=armor-policy-lab \
--no-preview
sleep 60
curl -s -o /dev/null -w "%{http_code}\n" "http://$LB_IP/?id=1%27%20OR%20%271%27%3D%271"
  1. Trigger the rate limit with a burst of 150 requests. The last requests in the burst and the follow-up check should return 429. The 300-request ban threshold is not reached:
Bash
for i in $(seq 1 150); do curl -s -o /dev/null "http://$LB_IP/"; done
curl -s -o /dev/null -w "%{http_code}\n" "http://$LB_IP/"
  1. Clean up in reverse order of creation. The load balancer bills while it exists, so do not skip this:
Bash
gcloud compute forwarding-rules delete armor-lab-fr --global --quiet
gcloud compute target-http-proxies delete armor-lab-proxy --quiet
gcloud compute url-maps delete armor-lab-map --quiet
gcloud compute backend-services delete backend-armor-lab --global --quiet
gcloud compute security-policies delete armor-policy-lab --quiet
gcloud compute health-checks delete health-check-armor --quiet
gcloud compute addresses delete armor-lab-ip --global --quiet
gcloud projects delete mumbai-armor-lab-2026 --quiet

Production Best Practices & Common Pitfalls

Common Mistake

Putting a public load balancer in front of an application with no Cloud Armor policy attached. A preconfigured WAF rule and a basic rate limit take only minutes to add and block the most common web attacks at the edge.

Tip

Create new rules with --preview first and read the policy's request logs in Cloud Logging. Enforce a rule with --no-preview only after confirming it does not match legitimate traffic. For rate limits, start with a generous threshold and tighten it gradually.

Security

Cloud Armor only protects traffic that passes through a supported load balancer. A VM with its own external IP bypasses the policy entirely, so close that path with firewall rules that accept traffic only from the load balancer.

  • Rely on Google-maintained WAF rules first. Rule sets such as sqli-v33-stable are updated as attack patterns change, similar to AWS WAF managed rule groups or Azure WAF managed rule sets. Use them before writing custom expressions for well-known attacks.
  • Tune sensitivity to cut false positives. Preconfigured rules support sensitivity levels, and you can exclude individual signature IDs that break a legitimate endpoint.
  • Plan rule order deliberately. Keep specific allow and deny rules at lower numbers than broad rules, and leave gaps (1000, 2000, 3000) so you can insert rules later.
  • Always set the enforcement key. Rate-limit rules without --enforce-on-key=ip count all traffic together, so one noisy client can trigger limits for everyone.
  • Enable backend service logging. Without it, Cloud Armor decisions do not appear in Cloud Logging and preview results cannot be reviewed.

Quick Reference & Troubleshooting Commands

Command Description
gcloud compute security-policies create NAME Create a Cloud Armor security policy
gcloud compute security-policies rules create PRIORITY --action=rate-based-ban Add a rate-limiting rule
gcloud compute security-policies rules create PRIORITY --expression="evaluatePreconfiguredExpr('sqli-v33-stable')" Add a preconfigured WAF rule
gcloud compute security-policies rules update PRIORITY --no-preview Enforce a rule that was in preview mode
gcloud compute backend-services update NAME --security-policy=POLICY --global Attach a policy to a backend service
gcloud compute security-policies rules list --security-policy=POLICY Review active rules and priorities

Resources

Artifact Registry

Google Cloud's current, unified package and container image storage service, the successor to the older Container Registry. It supports container images alongside language packages like npm, Maven, and Python packages in one service, and supports cleanup policies to automatically remove old, untagged image versions.

BigQuery

Google Cloud's serverless data warehouse for analytics, priced based on the volume of data a query actually scans rather than pre-provisioned compute capacity. Selecting only needed columns and querying a properly partitioned table's relevant date range are the two highest-impact levers for controlling BigQuery cost.

Bigtable (GCP)

A wide-column NoSQL database built for very high throughput at extremely low latency, suited to time-series data, IoT telemetry, and analytics workloads with massive write volume. It is a specialized tool distinct from Firestore's document model or Cloud SQL's relational model.

Billing Account (GCP)

A separate object from a Project that holds the actual payment method for Google Cloud usage. One Billing Account can be linked to many Projects, all of whose usage is billed to that same account, letting a company centralize payment while individual Projects retain their own separate IAM control over resources.

Cloud Armor

A security policy service attached to a Global External HTTP(S) Load Balancer, filtering malicious requests before they reach the backend. It supports rate-based rules blocking a single source IP exceeding a request threshold, and preconfigured WAF rules blocking common attack patterns like SQL injection, Google's equivalent of AWS WAF or Azure WAF.

Cloud Functions (GCP)

Google Cloud's event-driven, single-purpose compute service, the most granular and shortest-lived compute unit in GCP's compute spectrum. It fits a narrow niche compared to Cloud Run - a specific triggered action like resizing an uploaded image, rather than a full application with multiple routes and business logic.

Cloud Load Balancing

Google Cloud's family of load balancing products, spanning Global External HTTP(S) Load Balancers (public, distributed globally via a single IP), Regional External Load Balancers, and Internal Load Balancers reachable only from within the VPC. The right type depends on traffic type and whether the backend should ever be reachable from the public internet.

Cloud Logging

Google Cloud's service for collecting, storing, and querying log data from every GCP service and custom applications. Its query filter syntax lets logs be narrowed by resource, severity, and specific field values, and Log Sinks can route matching logs to BigQuery, Cloud Storage, or Pub/Sub for long-term retention beyond the default window.

Cloud Monitoring

Google Cloud's metrics, dashboards, and alerting service. An alert policy requires a Notification Channel explicitly attached to actually notify someone when it fires - without one, the policy still evaluates and logs its own firing history, but nobody is ever told, a common and easy-to-miss misconfiguration.

Cloud NAT

A service providing outbound-only internet connectivity for resources with no external IP address, GCP's equivalent of an AWS or Azure NAT Gateway. Cloud NAT requires a Cloud Router in the same region and provides zero inbound connectivity capability - a resource behind it remains completely unreachable from the internet.

Cloud Run

A fully managed, serverless platform for running containerized applications, scaling automatically to zero when idle and billing only for actual invocations. It combines the flexibility of running any container with zero OS management overhead, making it the right default for a standard stateless containerized web service.

Cloud SQL

Google Cloud's managed relational database service, supporting MySQL, PostgreSQL, and SQL Server. It is the right default for a traditional relational workload with moderate scale needs, handling patching, backups, and replication automatically without requiring OS-level access to the underlying database server.

Cloud Spanner

A globally distributed, strongly consistent relational database offering both SQL semantics and horizontal scalability beyond what a single Cloud SQL instance can provide. It is the right choice specifically when a workload needs both relational query capability and massive scale simultaneously, not simply because a workload feels large or important.

Cloud Storage Bucket

The top-level container for objects in Google Cloud Storage, GCP's object storage service equivalent to AWS S3 or Azure Blob Storage. Every object uploaded to Cloud Storage must belong to exactly one bucket, and bucket-level settings control default storage class, location, and access permissions for everything inside it.

Cloud VPN (GCP)

A service connecting an on-premises network to a GCP VPC over an encrypted tunnel, similar to VPN Gateway in Azure or a Site-to-Site VPN in AWS. It requires a Cloud Router as its foundation and is distinct from VPC Network Peering, which connects two GCP VPCs directly rather than an external network.

Compute Engine

Google Cloud's Infrastructure-as-a-Service offering, providing full virtual machines with complete OS-level control. It is the right choice specifically when a workload needs custom software, specific OS configurations, or hardware-level access that GKE and Cloud Run don't expose.

Error Reporting (GCP)

A Google Cloud operations service that automatically aggregates and groups application errors from logs and instrumented code, surfacing recurring error patterns and their frequency without requiring manual log searching for each individual occurrence.

Firestore

A serverless NoSQL document database built for mobile and web application data, flexible schemas, and real-time client synchronization. It is not a strong fit for workloads needing complex relational joins or multi-row transactions across unrelated entities, which point instead to Cloud SQL or Spanner.

GCP Audit Log

A specific category of Cloud Logging entry recording administrative actions and data access. Admin Activity logs (configuration changes) are always enabled and cannot be disabled; Data Access logs (who read or wrote actual data) are disabled by default for most services and must be explicitly enabled before that history exists.

GCP Firewall Rule

A rule defined at the VPC level controlling inbound or outbound traffic, applied using network tags or Service Accounts on instances rather than being tied to a specific subnet boundary. A firewall rule only affects VMs carrying the exact matching tag or identity - a VM without it is entirely unaffected, silently, with no error to flag the mismatch.

GCP Folder

An optional grouping node in the GCP resource hierarchy, sitting between the Organization and individual Projects. Folders are commonly used to group Projects by team, department, or environment, letting IAM permissions and Organization Policies be applied once at the Folder level rather than repeated across every Project inside it.

GCP IAM Role Types

Google Cloud IAM roles come in three types: Basic roles (Owner, Editor, Viewer) which are broad and legacy; Predefined roles curated by Google and scoped to a specific service's specific needs; and Custom roles built from individual permissions for access needs a predefined role doesn't precisely match.

GCP Organization

The top-level node in Google Cloud's resource hierarchy, tied to a Google Workspace or Cloud Identity domain. An Organization contains Folders and Projects, and policies or IAM permissions set at this level automatically apply to everything beneath it across the entire company.

GCP Project

The fundamental unit of organization in Google Cloud - every resource belongs to exactly one Project, which serves as the boundary for billing, IAM permissions, and API enablement. A Project has a permanent, globally unique Project ID chosen at creation and never changeable, distinct from its display name which can be updated freely.

GCP Quota

A default limit on how much of a specific resource (like VM CPUs or API calls) can be used per Project per region, designed to prevent runaway costs and protect shared infrastructure. Quotas can be checked and increased through the Console ahead of a known future need, such as a planned launch event.

GCP Storage Class

A pricing and access tier for Cloud Storage objects - Standard, Nearline, Coldline, or Archive - trading lower storage cost against higher retrieval cost and a longer minimum storage duration. Deleting or overwriting an object before its class's minimum duration elapses still bills as if it were stored the full minimum period.

GKE Autopilot

A mode of Google Kubernetes Engine where Google manages node provisioning, sizing, and patching entirely - you define workloads, and nodes appear automatically to run them, billed per pod resource request rather than per node. It is the lower-effort default for most containerized workloads, versus Standard mode's direct node pool control.

Managed Instance Group

A group of identical Compute Engine VMs created from an Instance Template and managed as a single unit, GCP's equivalent of an AWS Auto Scaling Group or Azure VM Scale Set. A Managed Instance Group can autoscale based on a metric like CPU utilization, adding or removing instances automatically within configured minimum and maximum bounds.

Network Tag (GCP)

A freeform string label attached to a Compute Engine VM at creation time, used to target firewall rules to specific VMs. Network tags are simple but can be forgotten or misspelled at scale, which is why Service Account-based targeting is often preferred for anything security-critical in a growing fleet.

OS Login

A Compute Engine feature that ties SSH access to a user's actual Google Identity and IAM permissions, rather than manually managing individual SSH public keys per VM. Enabling OS Login means revoking a departing employee's GCP access also immediately revokes their SSH access to every VM, with no separate key cleanup needed.

Organization Policy (GCP)

A constraint applied at the Organization, Folder, or Project level that restricts what resources are allowed to look like across everything beneath that level - for example, blocking external IP addresses on VMs or restricting allowed regions. Unlike IAM, which controls who can act, Organization Policy controls what configurations are permitted.

Persistent Disk (GCP)

The block storage attached to a Compute Engine VM, equivalent to an AWS EBS volume or Azure Managed Disk. Persistent Disks come in zonal (replicated within one zone, lower cost) and regional (synchronously replicated across two zones, survives a single zone failure) variants.

Security Command Center

Google Cloud's security posture management service, continuously scanning deployed resources against security best practices and surfacing specific, severity-ranked findings - like a publicly accessible storage bucket - rather than a single opaque score. Findings should be prioritized by actual severity, not treated as a count to minimize.

Service Account (GCP)

An identity used by applications, VMs, and automated processes to authenticate to Google Cloud APIs, rather than by a human user. A Service Account is itself also a resource with its own IAM permissions, and can be attached directly to a VM or impersonated temporarily, both safer alternatives to downloading its long-lived JSON key file.

Shared VPC

A configuration where one Project (the host) owns a VPC network, while other Projects (service projects) attach to it and deploy resources using its subnets. This centralizes network administration in the host Project while letting individual teams in service Projects still manage their own resources independently.

Spot VM (GCP)

A Compute Engine VM using Google's spare, unused capacity at a steep discount, with the trade-off that Google can reclaim the instance with short notice. Spot VMs are appropriate only for fault-tolerant, interruption-tolerant workloads like batch processing, never for customer-facing services needing reliable availability.

VPC (GCP)

A Virtual Private Cloud in Google Cloud is a global resource by default, unlike the regional VPC or VNet model in AWS or Azure - a single GCP VPC can span every region, with individual subnets defined per-region inside it. The default auto-mode VPC pre-creates a subnet in every region, while a custom-mode VPC starts empty until subnets are deliberately defined.

VPC Network Peering

A direct connection between two separate VPCs, potentially in different Projects or Organizations, with traffic never touching the public internet. Peering must be established from both sides to become active, and is explicitly non-transitive - if VPC A peers with B, and B peers with C, A cannot reach C without its own direct peering connection to C.

Explore More in GCP Operations, Security, and Production Readiness

All 6 Topics

Frequently Asked Questions

Is Protecting Web Applications with Cloud Armor free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Protecting Web Applications with Cloud Armor topic cover?

Configure Cloud Armor security policies with rate limiting and preconfigured WAF rules to block floods and SQL injection at the edge.

Found a mistake, an outdated step or a broken link?