GoogleCloudPlatform / python-docs-samples

Code samples used on cloud.google.com
Apache License 2.0
7.48k stars 6.45k forks source link

Could not connect to server: No such file or directory. PostgreSQL--> CloudSQL connection Error on Google App Engine #5680

Closed SohaibShafiq1 closed 3 years ago

SohaibShafiq1 commented 3 years ago

Is the server running locally and accepting connections on Unix domain socket "/cloudsql/connection-name/.s.PGSQL.5431"? Whenever i deploy and login for superuser, i recieve this error. My app.yaml:

runtime: python
env: flex
entrypoint: gunicorn -b :$PORT core.wsgi

automatic_scaling:
  min_num_instances: 1
  max_num_instances: 8
  cool_down_period_sec: 180
  cpu_utilization:
    target_utilization: 0.5
  target_concurrent_requests: 100

beta_settings:
  cloud_sql_instances: <connection-name>
runtime_config:
  python_version: 3

My Settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'HOST': config('DB_HOST'),
        'PORT': config('DB_PORT'),
        'NAME': config('DB_NAME'),
        'USER': config('DB_USER'),
        'PASSWORD': config('DB_PASSWORD')
    }
}
DATABASES['default']['HOST'] = '/cloudsql/<connection-name>'
if os.getenv('GAE_INSTANCE'):
    pass
else:
    DATABASES['default']['HOST'] = '127.0.0.1'

STATIC_URL = config('STATIC_URL')
STATIC_ROOT='static'
AUTH_USER_MODEL = 'users.NewUser'
MEDIA_URL='/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

I Run cloud_sql_proxy.exe file as well on port 5431. cloud_sql_proxy.exe -instances="<connection-name>"=tcp:5431 Deployment is successful but database connection is a problem. What is the solution for that.

kurtisvg commented 3 years ago

It looks like you are running the proxy on 127.0.0.1:5431 - the default postgres port is actually 5432.

You need to tell your app you want to connect on 127.0.0.1:5432 when running locally, and on /cloudsql/<INSTANCE_CONNECTION_NAME> when deployed.

If you're still having issues when deployed it's useful to check the following:

  1. You've spelled your instance connection name correctly (project:region:instance)
  2. That you have the Cloud SQL Admin API enabled
  3. That your service account has the correct permissions

You can also take a look at this documentation, which provides detailed instructions on how to connect: https://cloud.google.com/sql/docs/mysql/connect-app-engine-flexible

SohaibShafiq1 commented 3 years ago

@kurtisvg But when i run the proxy on port 5432 i got some error like: "listen tcp 127.0.0.1:5432: bind: An attempt was made to access a socket in a way forbidden by its access permissions."