Cloud Function - Connecting to Kubernetes container

5/15/2019

I want to connect from Google Cloud Function to Kubernetes (GKE) container. Specifically, the container has postgres database and I want to read records in a table.

In Golang:

func ConnectPostgres(w http.ResponseWriter, r *http.Request) {

    db, err := sql.Open("postgres", "postgresql://postgres@10.32.0.142:5432/myDatabase")

    if err != nil {
        http.Error(w, "Error opening conn:" + err.Error(), http.StatusInternalServerError)
    }
    defer db.Close()

    err = db.Ping()
    if err != nil {
        http.Error(w, "Error ping conn:" + err.Error(), http.StatusInternalServerError)
    }

    rows, err := db.Query("SELECT * FROM myTable")

    fmt.Println(rows)

    w.Write([]byte(rows))
}

10.32.0.142 is the Internal IP of the pod having the container.

But when the cloud function tries to Ping to postgres container, the request gets timed out.

How can I solve this?

-- user5155835
gke-networking
google-cloud-functions
google-cloud-platform
google-kubernetes-engine
kubernetes

2 Answers

5/16/2019

To connect from Cloud Function to GKE container from internal network, as @Cloud Ace mentioned you have to connect your Cloud Function to your VPC.

Otherwise, if you don't want to deal with connector, you can connect to your service on your GKE cluster, via public ip address of your LB or nodes.

In both cases, you have to create service and expose 5432 port to outside of your kubernetes cluster. You can't use directly pod ip addresses.

If you will go with vpc connector(internally) you can just use NodePort type service and use node's internal ip addresses.

But if you will go without vpc connector, also type: NodePort service will work with external/public ip addresses of nodes and you have to also add firewall rule for the nodes.

So I would suggest to use LoadBalancer type service for your postgres endpoint, because it will create Load Balancer on GCP with public ip address, and will create all forwarding and firewall rules automatically on GCP.

Hope it helps!

-- coolinuxoid
Source: StackOverflow

5/16/2019

You need to connect Cloud Function to VPC first, detailed here: https://cloud.google.com/functions/docs/connecting-vpc

-- Cloud Ace
Source: StackOverflow