docker compose: how to reference other service as localhost

Viewed 6587

I have two services - one is app and the other is db. This is a sketch of a docker compose file:

version: "2"
services:
  company:
    container_name: company-app
    extends:
      file: ../base-config.yml
      service: company
    links:
      - company-db
    env_file: ./company.env
    extra_hosts:
     - "local.company.com:127.0.0.1"

  company-db:
    container_name: company-db
    hostname: localhost
    extends:
      file: ../base-config.yml
      service: company-db
    env_file: ../db.env

Application service tries to connect to database on url jdbc:mysql://localhost/company_db

Which results in Communications link failure when running in docker container.

I've attached to running app container and check etc/hosts file and find next content:

root@d1a4391a83f4:/# cat etc/hosts
127.0.0.1   localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
127.0.0.1   local.company.com
172.18.0.3  d1a4391a83f4

As I understand the last entry added by docker compose is the ip by which i can reference db container, also I find out that it could be referenced by company-db domain.

Also as you see I've tried to add hostname option to company-db service, with no success.

My question is can I somehow by changing only compose configuration achieve ability to reference company-db service via same localhost url ?

3 Answers

Each container sees itself as localhost. Docker uses an internal DNS. So you can call your DB container like this:

jdbc:mysql://company-db/company_db

And remove the hostname of your DB.

You can use extra_hosts:

extra_hosts:
  - localhost:${COMPANY_DB_IP}

The downside is that you have to set the IP manually, and it can change :/

You can achieve this by mapping your localhost ports with containers. For your company-db service write the following

ports:
    - 3306:3306
Related