Search code examples
node.jsmongodbportgoogle-compute-engine

How to port forward Google Compute Engine Instance?


I've set up a VPS using the Google Compute Engine platform. In the instance, I've established a MongoDB database that's being locally hosted at the default port 21017. I've also set up a REST API based NodeJS server with express listening in on connections at port 8080.

Right now, I can only access the NodeJS site internally. How do I expose the VPS port 8080 to the external ip address so that I can access the API anywhere?

I tried following along an answer to this post: Enable Access Google Compute Engine Instance Via HTTP Port.

But that did not solve my issue


Solution

  • Default Firewall rules

    Google Compute Engine firewall by default blocks all ingress traffic (i.e. incoming network traffic) to your Virtual Machines. If your VM is created on the default network, few ports like 22 (ssh), 3389 (RDP) are allowed.

    The default firewall rules are documented here.

    Opening ports for ingress

    The ingress firewall rules are described here.

    The recommended approach is to create a firewall rule which allows port 8080 to VMs containing a specific tag you choose. Then associate this tag on the VMs you would like to allow ingress 8080.

    If you use gcloud, you can do that using the following steps:

    # Create a new firewall rule that allows INGRESS tcp:8080 with VMs containing tag 'allow-tcp-8080'
    gcloud compute firewall-rules create rule-allow-tcp-8080 --source-ranges 0.0.0.0/0 --target-tags allow-tcp-8080 --allow tcp:8080
    
    # Add the 'allow-tcp-8080' tag to a VM named VM_NAME
    gcloud compute instances add-tags VM_NAME --tags allow-tcp-8080
    
    # If you want to list all the GCE firewall rules
    gcloud compute firewall-rules list
    

    Here is another stack overflow answer which walks you through how to allow ingress traffic on specific ports to your VM using Cloud Console Web UI (in addition to gcloud).

    Static IP addresses

    The answer you linked only describes how to allocate a Static IP address and assign it to your VM. This step is independent of the firewall rules and hence can be used in combination if you would like to use static IP addresses.