Search code examples
mysqldockervirtual-machineexternal

Connect to External MYSQL docker container


I have two VM's running, one (A) has the MYSQL database inside a docker network. The other (B) VM has my front-end application docker container.

I run my MYSQL docker container (A) as follow:

docker run --name db --net=netname -v /path/to/mysql/:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=password  -d mysql:5.6.32

docker exec -i db mysql -pyourpassword -e 'CREATE DATABASE mydb'

After editing the MYSQL my.cnf file to bind-address = 0.0.0.0 I've tried to connect from VM (B) using the ip address given to me by the MYSQL docker container with ip addr show eth0 command.

which is:

 eth0@if46: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:ac:12:00:02 brd ff:ff:ff:ff:ff:ff
inet 172.18.0.2/16 scope global eth0
   valid_lft forever preferred_lft forever

host: 172.18.0.2 port: 3306

The response i receive:

OperationalError: (2003, "Can't connect to MySQL server on '172.18.0.2' ([Errno 110] Connection timed out)")

I've also tried VM (A) ip address but the response becomes connection refused

I'm sure i'm missing something -or many things- i'm open for enlightenment. How would i go about successfully connecting to (A) my MYSQL container from server (B) ? Thank you in advance.


Solution

  • You might as well just map the mysql port to the host.

    docker run -p 3306:3306 --name db --net=netname -v /path/to/mysql/:/var/lib/mysql
    -e MYSQL_ROOT_PASSWORD=password  -d mysql:5.6.32
    

    then you can access mysql using the host ip or name.

    If you are trying to reach containers directly by ip address.. in most cases that means you are doing it wrong. Assume the assigned ip is different every time you start it the container.