0
0
GcpHow-ToBeginner · 3 min read

How to Create a Firewall Rule in GCP: Step-by-Step Guide

To create a firewall rule in GCP, use the gcloud compute firewall-rules create command with parameters like --network, --allow, and --direction. This sets rules to allow or block traffic to your virtual machines based on IP ranges and protocols.
📐

Syntax

The basic command to create a firewall rule in GCP is:

  • gcloud compute firewall-rules create [RULE_NAME]: Names your firewall rule.
  • --network [NETWORK_NAME]: Specifies the network where the rule applies.
  • --allow [PROTOCOL:PORT]: Defines allowed protocols and ports, e.g., tcp:80.
  • --direction [INGRESS|EGRESS]: Sets traffic direction; ingress is incoming, egress is outgoing.
  • --source-ranges [IP_RANGE]: IP addresses allowed to send traffic (for ingress).
  • --target-tags [TAG]: Applies rule to VMs with this tag.
bash
gcloud compute firewall-rules create RULE_NAME \
  --network NETWORK_NAME \
  --allow PROTOCOL:PORT \
  --direction DIRECTION \
  --source-ranges IP_RANGE \
  --target-tags TAG
💻

Example

This example creates a firewall rule named allow-http that allows incoming HTTP traffic (port 80) from any IP address to VMs tagged with web-server in the default network.

bash
gcloud compute firewall-rules create allow-http \
  --network default \
  --allow tcp:80 \
  --direction INGRESS \
  --source-ranges 0.0.0.0/0 \
  --target-tags web-server
Output
Created [https://www.googleapis.com/compute/v1/projects/PROJECT_ID/global/firewalls/allow-http].
⚠️

Common Pitfalls

Common mistakes when creating firewall rules include:

  • Not specifying the correct --network, causing the rule to apply to the wrong network.
  • Forgetting to use --target-tags, so the rule does not apply to any VM.
  • Using overly broad --source-ranges that expose services to the internet unintentionally.
  • Confusing INGRESS and EGRESS directions.

Always double-check these parameters to avoid security risks or connectivity issues.

bash
Wrong:
gcloud compute firewall-rules create open-all \
  --allow tcp:22

Right:
gcloud compute firewall-rules create allow-ssh \
  --network default \
  --allow tcp:22 \
  --direction INGRESS \
  --source-ranges 192.168.1.0/24 \
  --target-tags ssh-access
📊

Quick Reference

ParameterDescriptionExample
RULE_NAMEName of the firewall ruleallow-http
--networkNetwork where rule appliesdefault
--allowProtocols and ports allowedtcp:80
--directionTraffic directionINGRESS or EGRESS
--source-rangesAllowed source IP ranges0.0.0.0/0
--target-tagsVM tags to apply ruleweb-server

Key Takeaways

Use the gcloud command with clear parameters to create firewall rules in GCP.
Specify network, allowed protocols, source IP ranges, and target VM tags carefully.
Ingress rules control incoming traffic; egress rules control outgoing traffic.
Avoid overly broad source ranges to keep your network secure.
Always test firewall rules to ensure they allow intended traffic and block unwanted access.