Docker – Using the host ip in docker-compose


I want to create a docker-compose file that is able to run on different servers.

For that I have to be able to specify the host-ip or hostname of the server (where all the containers are running) in several places in the docker-compose.yml.

E.g. for a consul container where I want to define how the server can be found by fellow consul containers.

  image: progrium/consul
  command: -server -advertise -bootstrap

I don't want to hardcode obviously.

I could use env_file: to specify the hostname or ip and adopt it on every server, so I have that information in one place and use that in docker-compose.yml. But this can only be used to specifiy environment variables and not for the advertise parameter.

Is there a better solution?

Best Answer

docker-compose allows to use environment variables from the environment running the compose command.

See documentation at

Assuming you can create a wrapper script, like @balver suggested, you can set an environment variable called EXTERNAL_IP that will include the value of $(docker-machine ip).


export EXTERNAL_IP=$(docker-machine ip)
exec docker-compose $@


# docker-compose.yml
version: "2"
    image: consul
    command: agent -server -advertise ${EXTERNAL_IP} -bootstrap

Unfortunately if you are using random port assignment, there is no way to add EXTERNAL_PORT, so the ports must be linked statically.

PS: Something very similar is enabled by default in HashiCorp Nomad, also includes mapped ports. Doc: