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-rangesthat expose services to the internet unintentionally. - Confusing
INGRESSandEGRESSdirections.
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
| Parameter | Description | Example |
|---|---|---|
| RULE_NAME | Name of the firewall rule | allow-http |
| --network | Network where rule applies | default |
| --allow | Protocols and ports allowed | tcp:80 |
| --direction | Traffic direction | INGRESS or EGRESS |
| --source-ranges | Allowed source IP ranges | 0.0.0.0/0 |
| --target-tags | VM tags to apply rule | web-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.