Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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.

like image 429
Omnipresent Avatar asked Oct 29 '25 15:10

Omnipresent


1 Answers

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!

like image 161
Augusto Avatar answered Oct 31 '25 05:10

Augusto