[Python] Can't connect to PostgreSQL, from Google Cloud Run to Google Cloud SQL

Discussão em 'Python' iniciado por Stack, Maio 8, 2025.

  1. Stack

    Stack Membro Participativo

    Sup?

    I want to connect to my PostgreSQL database on Cloud SQL from Cloud Run, and whatever I do, I get errors. The most annoying one is the "connection refused" error. I have tried anything you can imagine: "SQL client role", "Different connection strings", "Adding the client SQL connection", "Docs", "LLMs", anything you can imagine.

    I put the errors I receive in the logs here.May someone help me:

    sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server on socket "/cloudsql/<project_id>:<region_id>:<instance_id>/.s.PGSQL.5432" failed: Connection refused

    Cloud SQL connection failed. Please see https://cloud.google.com/sql/docs/mysql/connect-run for additional details: certificate had CN "", expected "<project_id>:<region_id>:<instance_id>"

    # Codes I have tried to connect so far:
    DB_CONFIG = {
    "drivername": "postgresql+psycopg2",
    "username": os.getenv("DB_USER"),
    "password": os.getenv("DB_PASS"),
    "database": os.getenv("DB_NAME"),
    "query": {
    "host": os.getenv("DB_HOST") # like this: /cloudsql/<project_id>:<region>:<instance_name>
    }
    }
    #or
    DB_CONFIG = {
    "drivername": "postgresql+psycopg2",
    "username": os.getenv("DB_USER"),
    "password": os.getenv("DB_PASS"),
    "database": os.getenv("DB_NAME"),
    "host": os.getenv("DB_HOST")
    }
    engine = create_engine(URL.create(**DB_CONFIG))
    # or using direct connection strings
    DATABASE_URL = os.getenv(
    "DATABASE_URL", "postgresql://<user>:<pass>@/<db_name>?
    host=/cloudsql/<project_id>:<region>:<instance_name>"
    )
    engine = create_engine(DATABASE_URL)

    Continue reading...

Compartilhe esta Página