简体   繁体   中英

Cannot connect to MySQL running in Docker from host machine

I have multiple MySQL servers running in separate docker containers. I'm not able to connect to either one from the host machine.

$ mysql -h172.17.0.2 -uroot -pPASSWORD
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2003 (HY000): Can't connect to MySQL server on '172.17.0.2' (60)

IP address from docker inspect:

$ docker inspect local2 | grep IPAddress
            "SecondaryIPAddresses": null,
            "IPAddress": "172.17.0.2",
                    "IPAddress": "172.17.0.2",

And ports exposed (but not mapped):

$ docker inspect local2 | grep -B1 3306
            "ExposedPorts": {
                "3306/tcp": {},
                "33060/tcp": {}
--
            "Ports": {
                "3306/tcp": null,
                "33060/tcp": null

The docker container was created (and recreated) with

docker run --name local -e MYSQL_ROOT_PASSWORD=PASSWORD -d mysql:8.0.21

And I can connect from another docker client on the network:

docker run -it --network bridge --rm mysql mysql -h172.17.0.2 -uroot -pPASSWORD

Also if I bash into the container I am able to connect locally with localhost.

I only can't connect from the host machine.

After some more research I found it's not actually possible to access the Docker instance on a Mac without mapping a port.

https://github.com/docker/for-mac/issues/2670#issuecomment-371249949

You cannot access container IPs directly on mac. You need to use localhost with port forwarding

See https://docs.docker.com/docker-for-mac/networking/#known-limitations-use-cases-and-workarounds

:(

I'd be happy to be wrong here..

I can't spot any problem in your way of accessing the service in the container. I just suspect that the service is not actually ready yet.

Maybe that'll give you an idea to troubleshoot:

passwd=pw
id=$(docker run --name some-mysql -e MYSQL_ROOT_PASSWORD="$passwd" --detach mysql)

ip=$(docker inspect --format '{{ .NetworkSettings.IPAddress }}' "$id")

printf "listing open ports on %s:\n You might have wait some seconds until they are open\n" "$ip"
nmap "$ip" -p 3306,33060

printf "connecting to %s:\n" "$ip"
mysql --host="$ip" --user="root" --password="$passwd" --protocol=TCP --wait

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM