从 docker 容器连接到远程 MySQL 数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36367100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Connect to remote MySQL db from docker container
提问by Brendenw
I'm working to containerize a Django 1.5.x application that connects to a MySQL DB on a separate server via ODBC:
我正在将一个 Django 1.5.x 应用程序容器化,该应用程序通过 ODBC 连接到单独服务器上的 MySQL 数据库:
[mysql_default]
database = DB_NAME
driver = /usr/lib64/libmyodbc5.so
server = REMOTE_DB_SERVER
user = DB_USER
password = DB_USER_PWD
port = 3306
I'm able to run the Django app on my local machine (outside docker) with a connection to the remote DB via port forwarding & SSH:
我可以在我的本地机器(docker 外部)上运行 Django 应用程序,并通过端口转发和 SSH 连接到远程数据库:
ssh -L 3307:127.0.0.1:3306 MYID@REMOTE_DB_SERVER
I've set up a Docker container for the app using Centos 6.x, but can't get the MySQL connection working. The container has MySQL installed and the mysqld running.
我已经使用 Centos 6.x 为应用程序设置了 Docker 容器,但无法使 MySQL 连接正常工作。容器已安装 MySQL 并运行 mysqld。
My docker-compose.yml file looks like this:
我的 docker-compose.yml 文件如下所示:
version: "2"
services:
web:
build: .
image: MY_IMAGE
container_name: MY_CONTAINER
network_mode: "host"
ports:
- "3307:3306"
command: /bin/bash
With the container running, I can execute the following command (outside the container) to show databases on the remote DB:
随着容器的运行,我可以执行以下命令(在容器外)来显示远程数据库上的数据库:
docker exec MY_CONTAINER echo "show databases" | mysql -u DB_USER -pDB_USER_PWD -h 127.0.0.1 --port=3307
But from inside 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)
回答by Danil Valov
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.
Docker 就像一个虚拟机一样工作。它有一个本地存储和一个本地环境。当您从 Docker 连接到 127.0.0.1 时,它会尝试连接到这个 Docker(而不是连接到运行 Docker 的本地机器),因为 Docker 的本地主机是 Docker。
Please, read the following answer:
请阅读以下答案:
From inside of a Docker container, how do I connect to the localhost of the machine?
回答by Brendenw
I solved this by using the docker host address instead of '127.0.0.1' for queries from within the container:
我通过使用 docker 主机地址而不是 '127.0.0.1' 来解决这个问题:
echo "show databases" | mysql -u DB_USER -pDB_USER_PWD -h 10.0.2.2--port=3306
echo "显示数据库" | 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:
由于 Docker 主机 ip 可能会有所不同,这篇文章描述了获取正确地址的步骤:
How to get the IP address of the docker host from inside a docker container