Error while connecting to a cloud sql instance via cloud proxy in django using cloud run

932 views Asked by At

I am trying to connect to cloud-sql for a django project in cloud run which is being deployed through cloud run in production. However Django throws me an error saying

Error: 'asia-south1' is not a valid port number.

My database settings in settings.py is as follows

if os.getenv('ENV') == 'PROD':
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'HOST': '/cloudsql/<PROJECT-NAME>:asia-south1:<INSTANCE-ID>',
            'PORT': '5432',
            'USER': <USER>,
            'PASSWORD': <PASSWORD>,
            'NAME': <DB_NAME>,
        }
    }

I saw one possible solution as redirecting cloud proxy connections to 127.0.0.1:3306 but for that I'd have to install cloud proxy on the docker container and authenticate right? Isn't that what cloud run provides us without any of that hassle? Is there anyway of connecting to the cloud sql instance without installing cloud proxy on the container and redirection?

1

There are 1 answers

3
guillaume blaquiere On

How you can see in the documentation here, the Cloud SQL connexion of Cloud Run opens a Unix socket

Once correctly configured, you can connect your service to your Cloud SQL instance's unix domain socket using the format: /cloudsql/INSTANCE_CONNECTION_NAME.

So, your Django configuration is set to open a connexion through TCP and thus look for an IP/DNS and a port.

To connect Django to a Unix socket, you can follow this example/tutorial