MySQL 从其他容器访问mysql容器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35429920/
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
Access to mysql container from other container
提问by Isky
I have setup docker container with mysql that expose 3306.
I've specified database user, database password and create a test db and give the privileges to new user.
In another container i want to accesso to this db.
So i set up new container with a simply php script that create new table in this db.
I know that mysql container's ip is 172.17.0.2 so :
我已经用 mysql 设置了 docker 容器,暴露了 3306。我已经指定了数据库用户、数据库密码并创建了一个测试数据库,并将权限授予新用户。
在另一个容器中,我想访问这个数据库。
所以我用一个简单的 php 脚本设置了新容器,该脚本在这个数据库中创建了新表。
我知道 mysql 容器的 ip 是 172.17.0.2 所以:
$mysqli = new mysqli("172.17.0.2", "mattia", "prova", "prova");
Than using mysqli i create new table and all works fine.
But i think that connect to container using his ip address is not good.
Is there another way to specify db host? I tryed with the hostname of the mysql container but it doens't work.
比使用 mysqli 我创建新表并且一切正常。
但我认为使用他的 IP 地址连接到容器并不好。
有没有另一种方法来指定数据库主机?我尝试使用 mysql 容器的主机名,但它不起作用。
回答by Tiago C
The --link
flag is considered a legacy feature, you should use user-defined networks.
该--link
标志被视为遗留功能,您应该使用用户定义的网络。
You can run both containers on the same network:
您可以在同一网络上运行两个容器:
docker run -d --name php_container --network my_network my_php_image
docker run -d --name mysql_container --network my_network my_mysql_image
Every container on that network will be able to communicate with each other using the container name as hostname.
该网络上的每个容器都可以使用容器名称作为主机名相互通信。
回答by sara
You need to link your docker containers together with --link flag in docker run command or using link feature in docker-compose. For instance:
您需要使用 docker run 命令中的 --link 标志或使用 docker-compose 中的链接功能将 docker 容器链接在一起。例如:
docker run -d -name app-container-name --link mysql-container-name app-image-name
In this way docker will add the IP address of the mysql container into /etc/hosts file of your application container. For a complete document refer to: MySQL Docker Containers: Understanding the basics
这样 docker 会将 mysql 容器的 IP 地址添加到您的应用程序容器的 /etc/hosts 文件中。有关完整文档,请参阅: MySQL Docker 容器:了解基础知识
回答by TvC
In your docker-compose.yml file add a link property to your webserver service: https://docs.docker.com/compose/networking/#links
在您的 docker-compose.yml 文件中,将链接属性添加到您的网络服务器服务:https://docs.docker.com/compose/networking/#links
Then in your query string, the host parameter's value is your database service name:
然后在您的查询字符串中,主机参数的值是您的数据库服务名称:
$mysqli = new mysqli("database", "mattia", "prova", "prova");