This is the default configuration one would have for a local postgresql connection using Django framework in setting.py file:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'LOCAL_DB_NAME',
'USER': 'LOCAL_DB_USER',
'PASSWORD': 'LOCAL_DB_PASS',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
How to configure it to work with Google Cloud Postgresql managed database?
Stay organized with collections Save and categorize content based on your preferences. Django apps that run on Google Cloud are running on the same infrastructure that powers all of Google's products, which generally improves the application's ability to adapt to a variable workload.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With