Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to another container using Docker compose

I need to use two containers together: one with Tomcat and another with a Database.

I have created the following yaml file which describes the services:

postgredb:
  image: postgres
  expose:
    - 5432
  ports:
    - 5432:5432
  environment:
    - POSTGRES_USER=user
    - POSTGRES_PASSWORD=password
tomcat:
  image:  tomcat
  links:
    - postgredb:db
  ports:
    - 8080:8080

After starting docker-compose I can see that I'm not able to reach the Database from Tomcat, unless I retrieve the IP address of the Database (via docker inspect) and use it when configuring Tomcat Connection Pool to the DB.

From my understanding, the two containers should be linked and I'd expect to find the database on localhost at port 5432, otherwise I see little benefits in linking the containers.

Is my understanding correct?

like image 694
Carla Avatar asked Mar 02 '16 14:03

Carla


People also ask

How do I connect two Docker composes?

If you set a predictable project name for the first composition you can use external_links to reference external containers by name from a different compose file. In the next docker-compose release (1.6) you will be able to use user defined networks, and have both compositions join the same network.

Can two Docker containers talk to each other?

A Docker network lets your containers communicate with each other. If you are running more than one container, you can let your containers communicate with each other by attaching them to the same network. Docker creates virtual networks which let your containers talk to each other.


1 Answers

Use the alias "db" that you have defined in file to refer to the database host name.

Containers for the linked service will be reachable at a hostname identical to the alias, or the service name if no alias was specified.

Source: https://docs.docker.com/compose/compose-file/compose-file-v2/#links

like image 113
Francesco Marchioni Avatar answered Oct 21 '22 13:10

Francesco Marchioni