Unix_socket mysql+aiomysql cloud run google failed

177 views Asked by At

I'm trying to connect to a database within the same project using unix_socket and the aiomysql library, below is an example of how I'm assembling the string, I'm using SQLALchemy but when I try to deploy it on cloud rum it just doesn't connect and the connection error, I am in doubt if I am assembling the string correctly below the example I am assembling

    connect_url = URL.create(
    'mysql+aiomysql',
    username=<USER>,
    password=<PASSWORD>,
    host=<HOST>,
    port=3306,
    database=<BANCO DE DADOS>,
    unix_socket='/cloudsql/project:region:instance',
)

In the aiomysql documentation it informs that it has the unix_socket option but it does not have a completed example

2

There are 2 answers

0
Rodrigo Martins On BEST ANSWER

I managed to solve the problem following the example of this link here on the google https://cloud.google.com/sql/docs/mysql/connect-run?hl=pt-br

I had to use the URL.Create from the SQLAlchemy library as follows

    unix_socket_path = '/cloudsql/<Projeto>:<Regiao>:<Instancia do Cloud mysql>'

  
connect_url = URL.create(
    'mysql+aiomysql',
    username='<User>',
    password='<Password>',
    host='<Host>',
    port=3306,
    database='<bd name>',
    query={"unix_socket": unix_socket_path}
)

Then I deployed it on Cloud Run and it worked perfectly, this configuration is necessary for accessing the Cloud Mysql database which is restricted, allowing access to applications that are within the same project. This worked perfectly for me.

0
Roopa M On

While connecting from cloud run, you should add Cloud SQL connection to the Cloud Run instance, as documented here.

If configured properly, you can access the Unix domain socket for your Cloud SQL instance on the environment's filesystem using the following path: /cloudsql/INSTANCE CONNECTION NAME.

The INSTANCE_CONNECTION_NAME uses the format project:region:instance-id.

Here's the correct format: postgres://<pg_user>:<pg_pass>@/<db_name>?host=/cloudsql/<cloud_sql_instance_connection_name>.

You can check this Github example

sqlalchemy.engine.url.URL.create(
            drivername="postgresql+pg8000",
            username=db_user,
            password=db_pass,
            database=db_name,
            query={"unix_sock": "{}/.s.PGSQL.5432".format(unix_socket_path)},
        )

Note: Some drivers require the unix_sock query parameter to use a different key. # For example, 'psycopg2' uses the path set to host in order to connect successfully.