Home  >  Article  >  Backend Development  >  How to Connect to a MySQL Server from a Go Application in Docker When Encountering \'Connection Refused\'?

How to Connect to a MySQL Server from a Go Application in Docker When Encountering \'Connection Refused\'?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 05:33:28558browse

How to Connect to a MySQL Server from a Go Application in Docker When Encountering

Error: Connection Refused When Connecting to MySQL Server from Go in Docker

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:

  1. Update the connection string in the Go code:
<code class="go">db, err = sql.Open("mysql", dbUser+":"+dbPassword+"@tcp(docker.for.mac.localhost:3306)/"+dbName)</code>
  1. If using Docker Compose, add the following line to the docker-compose.yml file under the service definition for the database container:
<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn