[Fixed]-How do you connect to Google Cloud Postgresql via Django framework?

23👍

First of all you need to set the database configuration look like so:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'DATABASE_NAME',
        'USER': 'DB_USER_NAME',
        'PASSWORD': 'DB_USER_PASS',
        # https://console.cloud.google.com/sql/instances
        'HOST': '<ip of your google instance>',
        'PORT': '5432', #at the moment of this writing google cloud postgresql is using the default postgresql port 5432
        'OPTIONS': {
            'sslmode': 'verify-ca', #leave this line intact
            'sslrootcert': '/your/path/to/server-ca.pem',
            "sslcert": "/your/path/to/client-cert.pem",
            "sslkey": "/your/path/to/client-key.pem",
        }
    }
}

Get ip/hostname from: https://console.cloud.google.com/sql/instances

To create and download the three pem files you need to visit something similar to this:
https://console.cloud.google.com/sql/instances/INSTANCE_NAME/ssl
And then click Client Certificate Button

To actually allow remote connection (if you are running django locally for development) then you need to click the AUTHORIZATION tab at the right (https://console.cloud.google.com/sql/instances/INSTANCE_NAME/authorization) and then enter your public ip or the public network of your organization. Only this ip/network will be allowed access.

To actually generate the instance along with choosing postgresql, generating the user and the password you need to follow this tutorial: https://cloud.google.com/sql/docs/postgres/quickstart

Now the regular python manage.py makemigrations --settings=settings.my_settings should work just fine


In case you need to verify the connection by using psql then you can connect using this command in terminal:

psql "sslmode=verify-ca sslrootcert=/your/path/to/server-ca.pem \
sslcert=/your/path/to/client-cert.pem \
sslkey=/your/path/to/client-key.pem \
hostaddr=<ip address of google cloud instance> \
user=<your db username> dbname=<your db name>"

you will be prompted for a password

Enjoy!

Leave a comment