Search code examples
google-cloud-platformfirewallgcp-vpc-firewall

How to redirect port for GCP compute instance using NAT rule for VPC Firewall


I have deployed Apache Tomcat 9 to the GCP compute instance (created via cloud console with tags: tomcat-web-host,http-server and https-server) which works fine on default ports 8080 and 8443 (created in VPC Firewall via terraform below).

resource "google_compute_firewall" "tomcat-on-vm" {
  project     = var.project_id
  name        = "tomcat-on-vm"
  network     = var.network
  description = "Creates firewall rule targeting tagged instances"

  allow {
    protocol  = "tcp"
    ports     = ["8080", "8443"]
  }

  target_tags = ["tomcat-web-host"]
}

Now I'm trying to map HTTP (port 80) and HTTPS (port 443) to 8080 and 8443 in a way which I will do the same way on-prem NAT as:

firewall-cmd --permanent --direct --add-rule ipv4 nat OUTPUT 0 -p tcp -o eth0 --dport 80 -j REDIRECT --to-ports 8080;

but that will take no effect (port 80 still not reachable). How can I do the same but in GCP VPC firewall for a compute instance?


Solution

  • Based on Google Support response my approach will not work there and an external load balancer may be solution to that problem

    The GCP doesn't implement unsolicited inbound connections from the internet. DNAT is only performed for packets that arrive as responses to outbound packets.

    Going with your case description, I understand what you are doing can be achieved via Load Balancer, for which you can setup LB to listen on frontend port 80 and send traffic on backend port 8080.