When trying to connect to a MySQL server from a Go application running within Docker, developers may encounter the following error:
dial tcp 127.0.0.1:3306: connect: connection refused
Cause:
By default, Docker containers run in isolated network spaces, making it impossible for applications running within to directly access the host machine's localhost.
Solution:
To resolve this issue, use the special hostname docker.for.mac.localhost instead of localhost. This address enables communication with the host machine's services by employing the Docker networking:
<code class="go">db, err = sql.Open("mysql", dbUser+":"+dbPassword+"@tcp(docker.for.mac.localhost:3306)/"+dbName)</code>
<code class="yml">ports: - "3306:3306"</code>
This will map the host machine's port 3306 to the container's port 3306, allowing the Go application to connect via the correct port.
The above is the detailed content of How to Connect to a MySQL Server from a Go Application in Docker When Encountering \'Connection Refused\'?. For more information, please follow other related articles on the PHP Chinese website!