Unable to access host's localhost from container

I am running a MySQL container with its 3306 port mapped to the host machine’s 127.0.0.1:3306.

However, I cannot access the host’s 127.0.0.1:3306 from another container via 172.17.0.1:3306. The connection only works when I map the MySQL container to 0.0.0.0:3306. But listening on 0.0.0.0 or use “–net=host” may pose security risks.

Rootless Docker provides a way to access the host’s loopback address via 10.0.2.2 . Does Rootful Docker offer a similar method? Thanks!

This is already the recommended solution. That is if this is really the ip for the docker0 network interface on your host, and mysql on your host actually binds the port 3306 on this ip.

Thank you for your answer!:slightly_smiling_face:
After binding the MySQL container to 172.17.0.1:3306, I can indeed access it from another container using the same address. But I’d also like to know is there a way for a container to access the host’s 127.0.0.1?

No. Containers are for isolation. You can not access 127.0.0.1 on the host from inside a container.

I missed a crucial detail: I seem to have skipped the first line and assumed mysql is running on the host.

Why would you want to use the published host port to access the database from another container?
The intended approach is to put the app container and database container in the same user defined network, then use dns-based service discovery to communicate from the app container to the database container.

The networks internal dns, will resolve the service name (docker compose only), container name, container’s hostname, or the container’s network alias to the current container ip, so you will be able to reach the application in the target container with either one of those names and the container port of the application.

This does not work with default bridge network.

The best practice is exactly as you said. But my server resources are limited, and it’s hosting several rootless user applications. Therefore, I plan to let them access the host’s 127.0.0.1:3306 so that they can share a single MySQL instance (running in a rootful Docker) and conserve resources.

In a rootless Docker, I can access the host’s 127.0.0.1 via 10.0.2.2 in container. However in a rootful Docker environment, it appears that unless MySQL is listening on 0.0.0.0, the service can’t be reached via the 172.17.0.1 gateway address.

Unless you want only specific containers to access the MySQL port, the docker bridge IP should be enough, but I wrote about a workaround here: