从其他容器访问mysql容器 [英] Access to mysql container from other container

查看:748
本文介绍了从其他容器访问mysql容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用mysql公开了3306并安装了docker容器. 我已指定数据库用户,数据库密码并创建测试数据库,并将特权授予新用户.
在另一个容器中,我想访问此数据库.
因此,我用一个简单的PHP脚本设置了新容器,该脚本在此db中创建了新表.
我知道mysql容器的ip是172.17.0.2,所以:

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 :

$mysqli = new mysqli("172.17.0.2", "mattia", "prova", "prova");

与使用mysqli相比,我创建了新表,并且一切正常.
但是我认为使用他的IP地址连接到容器不是很好.
还有另一种指定数据库主机的方法吗?我尝试使用mysql容器的主机名,但是它不起作用.

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.

推荐答案

您需要在docker run命令中将docker容器与--link标志链接在一起,或者在docker-compose中使用链接功能.例如:

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 -d -name app-container-name --link mysql-container-name app-image-name

这样,docker会将mysql容器的IP地址添加到应用程序容器的/etc/hosts文件中. 有关完整的文档,请参考: MySQL Docker容器:基本知识

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

这篇关于从其他容器访问mysql容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆