Connect to remote MySQL db from docker container

I am working on a container for a Django 1.5.x application that connects to a MySQL database on a separate server via ODBC:

[mysql_default] database = DB_NAME driver = /usr/lib64/libmyodbc5.so server = REMOTE_DB_SERVER user = DB_USER password = DB_USER_PWD port = 3306 

I can run the Django application on my local computer (external docker) with a connection to the remote DB via port forwarding and SSH:

  ssh -L 3307:127.0.0.1:3306 MYID@REMOTE _DB_SERVER 

I installed the Docker container for the application using Centos 6.x, but I cannot get the MySQL connection to work. The container has MySQL and mysqld is running.

My docker-compose.yml file looks like this:

 version: "2" services: web: build: . image: MY_IMAGE container_name: MY_CONTAINER network_mode: "host" ports: - "3307:3306" command: /bin/bash 

When starting the container, I can execute the following command (outside the container) to show the databases on the remote database:

 docker exec MY_CONTAINER echo "show databases" | mysql -u DB_USER -pDB_USER_PWD -h 127.0.0.1 --port=3307 

But from within the container, the same command fails:

  echo "show databases" | mysql -u DB_USER -pDB_USER_PWD -h 127.0.0.1 --port=3306 ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111) 
+5
source share
2 answers

Docker works like a virtual machine. It has local storage and local environment. When you connect to 127.0.0.1 from Docker, it tries to connect to this Docker (and not to the local computer on which Docker was running), since the local host for Docker is Docker.

Please read the following answer:

From inside the Docker container, how do I connect to the local machine host?

+2
source

I solved this using the docker host address instead of "127.0.0.1" for requests from the container:

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

Since the IP address of the Docker host can change, this message describes the steps to get the correct address:

How to get docker host IP address from docker container

+1
source

Source: https://habr.com/ru/post/1246272/


All Articles