25

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
  • 631
  • 5
  • 26
Carla
  • 3,064
  • 8
  • 36
  • 65

2 Answers2

45

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,573
  • 3
  • 14
  • 34
Francesco Marchioni
  • 4,091
  • 1
  • 25
  • 40
  • 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
  • 2
    to make this a little clearer: if you have something written like base_url_api = "http://127.0.0.1:4999/" and you have a service called "api", then you can write base_url_api = "http://api:4999/" you actually dont even need to involve network: alias: – rictuar Oct 29 '22 at 19:50
2

For newer versions of docker-compose

Links are a legacy option. We recommend using networks instead.

version: "3"

services:
  web:
    image: "nginx:alpine"
    networks:
      - new

  worker:
    image: "my-worker-image:latest"
    networks:
      - legacy

  db:
    image: postgredb
    networks:
      new:
        aliases:
          - db
      legacy:
        aliases:
          - postgredb

networks:
  new:
  legacy:
Aalkhodiry
  • 2,178
  • 30
  • 25