Error: "dial tcp 127.0.0.1:3306: connect: connection refused" When Connecting to MySQL from Go in Docker
In an attempt to connect to a MySQL server running on a Mac using Go and Docker, an error message appears: "dial tcp 127.0.0.1:3306: connect: connection refused." This error occurs despite successfully connecting to the database on localhost:3306 using Navicat for MySQL.
This error is encountered due to the nature of Docker's isolation on Mac. Docker runs in a virtual machine (VM) under the surface, making it difficult to access services provided by the host machine directly.
To resolve this issue, adjust your connection string to use docker.for.mac.localhost:3306 instead of 127.0.0.1:3306. This special hostname allows communication between the Docker container and the host machine.
The amended Go code should look like this:
<code class="go">db, err = sql.Open("mysql", dbUser+":"+dbPassword+"@tcp(docker.for.mac.localhost:3306)/"+dbName)</code>
This modification should resolve the connection issue and enable communication between your Go application and the MySQL server running on the host machine.
The above is the detailed content of Why Can\'t My Go App in Docker Connect to MySQL on my Mac?. For more information, please follow other related articles on the PHP Chinese website!