Home  >  Article  >  Backend Development  >  How to Resolve \"dial tcp 127.0.0.1:3306: connect: connection refused\" Error When Connecting to a MySQL Server in Docker?

How to Resolve \"dial tcp 127.0.0.1:3306: connect: connection refused\" Error When Connecting to a MySQL Server in Docker?

DDD
DDDOriginal
2024-10-28 15:59:01337browse

How to Resolve

Unresolved Dial TCP Issue to MySQL Server via Docker

Unable to establish a connection to a MySQL server running in Docker? You're not alone. Let's delve into this common issue and explore a potential solution.

The Problem:

You encounter the "dial tcp 127.0.0.1:3306: connect: connection refused" error when attempting to connect to a MySQL database from within a Docker container using Go. Your MySQL server is functional on localhost:3306, but the connection from your Go application fails.

The Solution:

The crux of the issue lies in Docker's isolation. By default, Docker containers run in a network environment isolated from the host system. This separation prevents containers from directly accessing services provided by the host machine, including your MySQL server running on localhost.

To circumvent this limitation, you can modify your connection string to specify the IP address of the host machine using the special hostname docker.for.mac.localhost. The revised connection string should resemble this:

db, err = sql.Open("mysql", dbUser+":"+dbPassword+"@tcp(docker.for.mac.localhost:3306)/"+dbName)

By amending the hostname to docker.for.mac.localhost, your Docker container can establish a connection with the MySQL server running on your host machine through a network bridge.

Additional Notes:

For further guidance and troubleshooting tips, refer to the Docker documentation on networking. Remember that this workaround may require additional network configuration depending on your specific setup.

The above is the detailed content of How to Resolve \"dial tcp 127.0.0.1:3306: connect: connection refused\" Error When Connecting to a MySQL Server in Docker?. 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