Docker compose: bind multiple hosts to dynamic container's IP

Viewed 2345

I declare my service in docker-compose.yml like this:

wildfly:
  image: "myrepo/wildfly:latest"
  hostname: wildfly

So, compose adds entry to /etc/hosts:

172.18.0.4      wildfly

Where 172.18.0.4 is generated automatically by docker.

But I need to bind some.host.name to this generated IP in /etc/hosts to have multiple entries in /etc/hosts:

172.18.0.4      wildfly
172.18.0.4      some.host.name

How can I do that?

I tried to use extra_hosts syntax, but in docker-compose.yml I have no idea what IP will be assigned to container.

Have anybody faced the similar problem?

1 Answers

You should version '3' format of the compose which supports aliases. Since you are already using a supported docker version

version: '3'
services:
  wildfly:
    image: "myrepo/wildfly:latest"
    hostname: wildfly
    networks:
      default:
        aliases:
          - some.host.name

This won't add host entries since docker now uses its own internal DNS server. If you need to use multiple compose files to be able to reach the services. Then you should create an external network

docker network create commonnet

And then use below in your compose

version: '3'
services:
  wildfly:
    image: "myrepo/wildfly:latest"
    hostname: wildfly
    networks:
      commonnet:
        aliases:
          - some.host.name
networks:
  commonnet:
    external: true
Related