Docker – Refer to multiple hostnames in a Docker container using compose file

docker

We are running a bunch of services in their own containers via Docker, and we connect them using Docker Compose.

Previously we used linking to refer to other hosts, but the problem with that is that if a container is restarted and gets a new IP address then the linked nodes won't know about this and would stop working.

So we went with creating a network and naming our hosts and this works fine. However we have a mock component which we use for testing which replaces two of the other containers. I could configure this via links easily, but I don't know how to do this with networking.

Originally it was like:

mm:
  extends:
    file: common-service.yml
    service:  mm-container
  links:
    - mock:enet
    - mock:ff

(where mm is the container that knows about the containers enet and ff, and in this compose file used for testing we link them to the mock container instead.)

I tried adding this instead of the links:

extra_hosts:
  - "enet:mock"
  - "ff:mock"

(where enet and ff are the mocked hostnames) but of course this would add these lines to /etc/hosts as-is, so no hostname resolution takes place.

Is there a solution for this in Docker-land, or do we have to rewrite our mocking tool?

Best Answer

You can define network aliases on your mock container. Everyone on the network with those aliases defined will see them, so you may need to adjust your networks to prevent other containers from seeing it. E.g.

version: '3'

networks:
  mocknet:

services:
  mm:
    image: mm:latest
    networks:
      default:
      mocknet:

  other_svc:
    image: other_image:latest

  mock:
    image: mock:latest
    networks:
      mocknet:
        aliases:
        - ff
        - enet

If everything in this stack is allowed to resolve ff and enet to the mock service, then you can do away with mocknet and just set the aliases on the default network.

Related Topic