'Can't connect to local MySQL server through socket '/cloudsql/my-gcp-project:europe-west2:instance'

I'm getting an error when trying to connect to a MySQL server using a service in Cloud Run. This is the method I'm using to connect:

def get_connection(self) -> mysql.connector.connection.MySQLConnection:
    """ Get a connection to the database

    Returns:
        mysql.connector.connection.MySQLConnection: Connection to the
            database"""
    db_socket_dir = '/cloudsql'

    config = {
        'user': self.user,
        'password': self.password,
        'host': self.host,
        'client_flags': [ClientFlag.SSL],
        'ssl_ca': './ssl/server-ca.pem',
        'ssl_cert': './ssl/client-cert.pem',
        'ssl_key': './ssl/client-key.pem',
        'database': self.database
    }

    if os.environ['LOCAL_RUN'] == "no":
        config['unix_socket'] = '{}/{}'.format(
            db_socket_dir,
            self.instance_connection_name
        )
    else:
        config['port'] = 3307

    return mysql.connector.connect(**config)

Notably, this works fine when I run everything locally. I.e. when I have a proxy server running and my service running in terminal. I have also used this method in another service and it worked. My feeling is that it is linked to the error message saying "Can't connect to local MySQL server" because I am not intentionally trying to connect to a local server, but I can't figure why the method would think I am.

Other context, the value of 'host' is the Public IP address for my instance.

Any ideas?

I have looked at a lot of other similar questions on here but nothing seems to provide an answer to my exact problem.

The full error message is:

Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 2073, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 1518, in 
    full_dispatch_request
      rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 1516, in 
    full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.9/site-packages/flask/app.py", line 1502, in 
    dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  File "/app/main.py", line 28, in run_query_ep
    sql = SQL()
  File "/app/SQL.py", line 29, in __init__
    self.connection = self.get_connection()
  File "/app/SQL.py", line 58, in get_connection
    return mysql.connector.connect(**config)
  File "/usr/local/lib/python3.9/site-packages/mysql/connector/__init__.py", line 272, in connect
    return CMySQLConnection(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/mysql/connector/connection_cext.py", line 85, in __init__
    self.connect(**kwargs)
  File "/usr/local/lib/python3.9/site-packages/mysql/connector/abstracts.py", line 1028, in connect
    self._open_connection()
  File "/usr/local/lib/python3.9/site-packages/mysql/connector/connection_cext.py", line 241, in _open_connection
    raise errors.get_mysql_exception(msg=exc.msg, errno=exc.errno,
  mysql.connector.errors.InterfaceError: 2002 (HY000): Can't connect to local MySQL server through socket '/cloudsql/my-gcp-project:europe-west2:instance' (2)

EDIT:

I'm using a cloudbuild.yaml file to deploy the service:

steps:
  - name: "gcr.io/cloud-builders/docker"
    args:
      - build
      - "--no-cache"
      - "-f"
      - "backend/SQL/Dockerfile"
      - "-t"
      - "gcr.io/$PROJECT_ID/sql:${SHORT_SHA}"
      - "./backend/SQL"
    id: Build
  - name: gcr.io/cloud-builders/docker
    args:
      - push
      - "gcr.io/$PROJECT_ID/sql"
    id: Push
  - name: "gcr.io/google.com/cloudsdktool/cloud-sdk:slim"
    args:
      - run
      - deploy
      - sql
      - "--image=gcr.io/$PROJECT_ID/sql:${SHORT_SHA}"
      - "--add-cloudsql-instances=${_CLOUD_SQL_ADDRESS}"
      - "--service-account=sql-service@my-gcp-project.iam.gserviceaccount.com"
      - "--region=europe-west2"
      - "--platform=managed"
      - "--allow-unauthenticated"
      id: Deploy
      entrypoint: gcloud

tags:
  - gcp-cloud-build-deploy-cloud-run
  - gcp-cloud-build-deploy-cloud-run-managed
  - sql


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source