如何使用docker-compose链接两个容器 [英] How to link two containers using docker-compose
问题描述
目前,我有两个容器是根据图片构建的,然后将两个容器链接起来:
At the moment I have two containers which I build from an image and then link the two:
例如:
#mysql
docker build -t my/mysql docker-mysql
docker run -p 3306:3306 --name mysql -d my/mysql:latest
#webapp
docker build -t my/tomcat:7.0 tomcat/7.0
docker run -d --link mysql --name tomcat7 my/tomcat:7.0
由于我将 webapp
容器与 mysql
容器链接,所以 webapp
容器将获得一个 MYSQL_PORT_3306_TCP_ADDR
环境变量已创建.我使用此环境变量,然后在 jdbc
字符串中连接到mysql数据库.
Since I'm linking the webapp
container with mysql
container, the webapp
container gets a MYSQL_PORT_3306_TCP_ADDR
environment variable created. I use this environment variable to then connect to the mysql database in my jdbc
string.
所有这些都可以正常工作,但是现在我想使用 docker-compose
,以便可以从一个命令构建和运行所有内容.
All of this works fine but now I'd like to use docker-compose
so that everything can be built and ran from one command.
但是,在玩docker-compose时,我注意到它在图像名称前加上 docker _
前缀,并且进一步弃用了 link
选项.
However, while playing with docker-compose I'm noticing that it prefixes docker_
to the image name and furthermore deprecates the link
option.
问题
以上构建/运行命令将如何转换为docker-compose yml文件,以便webapp容器可以连接到jdbc的mysql容器.
How would the above build/run commands translate to docker-compose yml file such that the webapp container can connect to the mysql container for jdbc.
推荐答案
这里是对docker-compose的粗略翻译.
Here is a rough translation to a docker-compose.
请注意,docker-compose将其标记为自己的图像,因此,假设您在名为 test
的目录中创建了一个 mysql
图像,则容器名称将变为test_mysql_1
.1附加在末尾,因为您可以使用docker-compose扩展多个容器.
Note that docker-compose tags it's own images, so say you made a mysql
image in a directory named test
, then the container name would turn into test_mysql_1
. The 1 is appended on the end because you can scale up multiple containers using docker-compose.
此文件也采用此文件结构
This file also assumes this file-structure
├── docker-mysql
│ └── Dockerfile
├── tomcat
│ └── 7.0
│ └── Dockerfile
└── docker-compose.yml
version: '2'
services:
mysql:
build:
context: "./docker-mysql"
hostname: mysql
ports:
- "3306:3306"
webapp:
build:
context: "./tomcat/7.0"
hostname: tomcat7
links:
- mysql
这篇关于如何使用docker-compose链接两个容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!