问题
At the moment I have two containers which I build from an image and then link the two:
For example:
#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
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.
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.
However, while playing with docker-compose I'm noticing that it prefixes docker_
to the image name and furthermore deprecates the link
option.
Question
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.
回答1:
You need to add an alias
attribute in the compose yml. The following is taken from the docs the docs and is a very short example
web:
links:
- db
- db:database
- redis
That compose snippet defines a web
container which has to be linked to the db and redis containers and it also adds the db
container with the alias `database.
In you case, I think the yml for the tomcat container would look something like this
mysql:
image: my/mysql:latest
ports:
- "3306:3306"
tomcat7:
image: my/tomcat:7.0
links:
- mysql
Bear in mind that the tomcat container is not exposing any ports!
回答2:
Here is a rough translation to a 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
来源:https://stackoverflow.com/questions/35729083/how-to-link-two-containers-using-docker-compose