Search code examples
pythonpostgresqlpsycopg2google-cloud-sqlvpc

Config for using psycopg2 to access to Cloud SQL instance


I am using a PostgreSQL in Cloud SQL along with psycopg2 library to connect to database from my python code. The current one that I have is associated with a VPC network in which my google compute engines also in that VPC. So, in this case, my config to connect to this cloud sql instance can use private ip and my config look like this:

config['db-cloudsql'] = {
   "host" : "10.x.x.x" # cloud sql private ip address
   "user" : "postgres"
   "password" :"xxxxx"
   "database" : "postgres" 
}

But now I have another vm instance from another VPC network that need to access to this cloud sql instance. I know that I can access to the cloud sql instance using public ip. (by adding my vm to authorised network) But this vm need to access to the cloud sql instance very often. So I am not sure that the cost from accessing with public ip will be higher compared with accessing with private ip (cannot find any related document about this). I tried peering 2 vpc networks for accessing with private ip but just found that I cannot use this method to connect to sql with private ip from this document

I have found from the document that I can use instance connection name as a host for my config so it should be something like:

config['db-cloudsql'] = {
   "host" : "project-name:asia-southeast1:mydbname" #instance connection name
   "user" : "postgres"
   "password" :"xxxxx"
   "database" : "postgres" 
}

I haven't try this method yet, it might not working but if it somehow works, how will it differ from using public ip addess in term of cost?

Thank you


Solution

  • It seems like your question boils down into two parts:

    Are there any alternatives to public IP or private IP?

    No. You have to use one or the other to connect to your Cloud SQL instance. Private IP allows access from a VPC, Public IP is used pretty much everywhere else.

    Cost of public IP vs private IP

    You can find a breakdown of the costs here. In short, there is not really any extra charges with a Public IP. You do have to pay $.01 per hour while the instance is idle (to reserve the public IP address), and just like private IPs, you are responsible for costs of the Network Egress between regions.

    I can use instance connection name as a host for my config

    This is incorrect. If you are using the Cloud SQL Proxy to connect, it can create a Unix domain socket (at /cloudsql/INSTANCE_CONNECTION_NAME) that can be used to connect to your instance. However the proxy only authenticates your connection - it still needs a valid connection path (Public vs Private).