Home > Backend Development > Golang > Why Can\'t My Go App in Docker Connect to MySQL on my Mac?

Why Can\'t My Go App in Docker Connect to MySQL on my Mac?

Patricia Arquette
Release: 2024-10-29 07:07:02
Original
537 people have browsed it

Why Can't My Go App in Docker Connect to MySQL on my Mac?

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

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!

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