Connecting cloud run to compute engine

Hi @GeekyMechanic ,

Thank you for providing the details of your setup. If the PostgreSQL server on your Compute Engine VM is running fine, listening on the right port, and you have allowed incoming connections from the appropriate sources through the firewall rules, the issue might be related to the VM’s internal networking and the Cloud Run VPC Connector. You can consider checking the following:

  1. VPC Connector Configuration
    Make sure to review your Cloud Run VPC Connector settings. Check if it’s correctly set up and connected to the specific Cloud Run service you want to use to connect to the Compute Engine VM. Also, confirm that you’ve chosen the right VPC network and subnet for the connector.

  2. Private IP Range Conflict
    Confirm that the IP address of your Compute Engine VM (10.162.0.17) does not conflict with any other resources within your VPC network.

  3. Check PostgreSQL Configuration
    Check the PostgreSQL configuration on the VM to make sure it’s set to listen on the private IP, not just localhost. Also, make sure that PostgreSQL permits connections from the IP address range of the Cloud Run VPC Connector.

Also, from the error message indicated that the Ubuntu firewall is inactive, it may not be allowing incoming connections to the PostgreSQL service, even if you have allowed them in Google Cloud’s firewall rules. To enable the UFW firewall on your Compute Engine VM, follow these steps:

  1. Open a terminal or use an SSH client to connect to your Compute Engine VM.
  2. Run sudo ufw status
  3. If UFW is currently inactive, enable it using sudo ufw enable
  4. After enabling UFW, you’ll need to configure the firewall rules to allow incoming connections on the PostgreSQL port (5432). Usesudo ufw allow 5432
  5. If you need to restrict the source IP range for security reasons, you can specify the source IP or IP range when creating the rule. For example:
    sudo ufw allow from <source_IP_or_range> to any port 5432
  6. Verify that UFW is now active and that the rule for PostgreSQL is set correctly. Type in sudo ufw status
  7. After making changes to UFW, you might need to restart the PostgreSQL service to ensure that it can accept incoming connections. Use sudo systemctl restart postgresql

After enabling UFW and permitting incoming connections on the PostgreSQL port, try connecting again from your Cloud Run service. If everything is configured properly, you should no longer encounter the “Connection refused” error, and your Cloud Run service will be able to connect to the PostgreSQL database on the Compute Engine VM