'How to connect to MySQL server on localhost from inside of a Docker container in a windows machine?

I have seen the other ticket on Linux. My issue is on Windows.

I want my Java code running inside a Container to connect to MySQL on localhost OR i.e. 127.0.0.1.

I am able to connect to MySQL with either localhost or 127.0.0.1, from the host, but not from within the container.

I've also tried the network option which is --net="host".



Solution 1:[1]

The net=host option does not work with Docker for Windows.

To connect to the host machine, you need to get the ip of the host machine on the docker network interface, and use that ip to connect.

Run the command ipconfig on you windows machine, and get the ip of the docker interface. Inside the container use that IP to connect to MYSQL running on the host machine.

Solution 2:[2]

I had to do two things in similar scenario:

  • As noted here, you might need to open local MySql console and to privilege (user should be created at first) the mysql user:

    CREATE USER 'myuser1'@'localhost' IDENTIFIED BY 'pass123';
    GRANT ALL PRIVILEGES ON your_db_name.* TO 'myuser1'@'localhost';
    FLUSH PRIVILEGES;

    (instead of localhost you might also try your local network IP address, i.e. 192.168.1.123, or might be even a docker-IP address, like 172.1.x.x )

  • When connecting from application, in MySql host&port you might need to use host.docker.internal:3306 (or whatever port). If that doesn't succeed, use local network IP address there too.

Solution 3:[3]

docker.for.win.localhost does work if you are trying to connect mysql(service in windows localhost) from django docker container. keep 'HOST': 'docker.for.win.localhost', in setting.py

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 yamenk
Solution 2
Solution 3 Anil