Search code examples
mysqlauthenticationgoogle-cloud-sqltelnetcloud-sql-proxy

cloud-sql-proxy works with telent fails with mysql


I've got a GCP Cloud SQL instance, and I'm trying connect via the mysql client program on the shell via cloud-sql-proxy (version 2).

I start the proxy as such

cloud-sql-proxy project:regon:name -g 
2023/04/29 23:15:30 Authorizing with gcloud user credentials
2023/04/29 23:15:32 [project:regon:name] Listening on 127.0.0.1:3306
2023/04/29 23:15:32 The proxy has started successfully and is ready for new connections!

netstat confirms the proxy is listening on the expected host and port

netstat -ant | grep :3306
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN 

Connecting via mysql -h 127.0.0.1 --port=3306 fails, there's no output from the proxy when I run this either

mysql -v -h 127.0.0.1 -u myuser -p
Enter password: 
ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)

However if I try via telnet, it seems to work

telnet 127.0.0.1 3306
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Q
/m7bEb j-Z(%G
             L[mysql_native_password

and there's output from the proxy to boot

2023/04/29 23:15:39 [project:regon:name] instance closed the connection
2023/04/29 23:22:22 [project:regon:name] accepted connection from 127.0.0.1:58854

I can connect with gcloud sql connect project:regon:name --user=myuser, however I want to connect via mysql so I can chain it to other programs on the shell.

The mysql client binary I have is from ubuntu. Short of building it from scratch with debugging flags, can someone help me connect to my Cloud SQL instance via cloud-sql-proxy?

UPDATE:

I realized I'm mapping mysql to docker run -it --rm mysql:8 mysql $@;


Solution

  • After checking the mysql binary on my system with which mysql, I discovered instead of installing the binary from Apt like I'd assumed, I was instead using a thin wrapper script

    #!/bin/bash
    docker run -it --rm mysql:8 mysql $@
    

    The goal being to install as few packages from Apt as possible. However I forgot, and since cloud-sql-proxy is listening on 127.0.0.1 on the host, I was passing -h 127.0.0.1 to the mysql command...

    Docker was routing this to the local interface on the container instead of the host. Adding the --network=host flag to the container command passes the -h 127.0.0.1 flag to mysql to the host, and everything works as expected.

    #!/bin/bash
    docker run -it --network=host --rm mysql:8 mysql $@