Connect to remote MySQL db from docker container Connect to remote MySQL db from docker container mysql mysql

Connect to remote MySQL db from docker container


The Docker works like a virtual machine. It has a local storage and a local environment. When you connect to 127.0.0.1 from the Docker it tries to connect to this Docker (not to local machine where the Docker was runned) because the localhost for the Docker is the Docker.

Please, read the following answer:

From inside of a Docker container, how do I connect to the localhost of the machine?


I solved this by using the docker host address instead of '127.0.0.1' for queries from within the container:

echo "show databases" | mysql -u DB_USER -pDB_USER_PWD -h 10.0.2.2 --port=3306

Because Docker host ip can vary, this post describes steps to get the right address:

How to get the IP address of the docker host from inside a docker container