21

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?

Scott Anderson
  • 592
  • 4
  • 21
Carla
  • 2,566
  • 3
  • 26
  • 51

1 Answers1

40

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

oxr463
  • 1,273
  • 3
  • 13
  • 30
Francesco Marchioni
  • 3,888
  • 22
  • 36
  • 2
    What is the source of this quote? – oxr463 Feb 27 '20 at 12:34
  • 1
    @rage it looks like the source is https://docs.docker.com/compose/compose-file/compose-file-v2/#links, with a few words modified – AnhellO May 13 '20 at 03:58
  • You might be able to help me, I can't find a solution for my issue https://stackoverflow.com/questions/68589288/how-to-connect-to-named-networks-in-docker-compose – Zied Hamdi Jul 30 '21 at 13:53