Missing socket for connection to Cloud SQL from Google App Engine standard environment

Solution 1:

I am able to get the connection working with the following configuration:

PROJECT=[[YOUR-PROJECT-ID]]
REGION=europe-west3
INSTANCE=instance-01

and:

import os

from flask import Flask

import psycopg2

db_user = os.environ.get('CLOUD_SQL_USERNAME')
db_pass = os.environ.get('CLOUD_SQL_PASSWORD')
db_name = os.environ.get('CLOUD_SQL_DATABASE')
db_conn = os.environ.get('CLOUD_SQL_INSTANCE')

app = Flask(__name__)


@app.route('/')
def main():
    host = '/cloudsql/{}'.format(db_conn)

    cnx = psycopg2.connect(
        dbname=db_name,
        user=db_user,
        password=db_pass,
        host=host
    )
    with cnx.cursor() as cursor:
        cursor.execute('SELECT NOW() as now;')
        result = cursor.fetchall()
    current_time = result[0][0]
    cnx.commit()
    cnx.close()

    return str(current_time)

and:

flask==1.0.2
psycopg2==2.8

and, with ${VARIABLE} replaced with value:

runtime: python37
env_variables:
  CLOUD_SQL_INSTANCE: "${PROJECT}:${REGION}:${INSTANCE}"
  CLOUD_SQL_USERNAME: ${USERNAME}
  CLOUD_SQL_PASSWORD: ${PASSWORD}
  CLOUD_SQL_DATABASE: ${DATABASE}

Solution 2:

Based on a similar issue, the most probable root cause is detailed here: https://issuetracker.google.com/117804657#comment16

Other possible causes, per the discussion, could be:

  • A lack of public IP on the SQL instance
  • Specification of the port in the configuration settings

Here are some recommendations:

  • Run the application locally to make sure it works before deploying to App Engine.
  • Double check the Cloud SQL configuration (e.g. username, password, instance connection name) on the app.yaml file.
  • Make sure the Google Cloud SQL API is enabled.
  • Try recreating the Cloud SQL instance.

Simply recreating the Cloud SQL instance or database has worked in other cases, as modifications to the quickstart’s default setup might be difficult to track.

Cheers