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

Linda Hamilton
Release: 2024-10-30 05:33:28
Original
559 people have browsed it

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
Copy after login

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>
Copy after login
  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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template