Search code examples
dockerdocker-composedocker-network

How to find exposed port of linked service with Docker Compose v2 format?


In docker-compose legacy yml if you link a service it used to create an environment variable servicename_PORT which you could use to discover the port of a linked container. In the new v2 format we have user defined networks which add the service name to the internal DNS and so we can connect to linked services, but how do we find the port a linked service exposes? The only way I can think of is to create an environment variable for each linked service where I can put the port, but then I will have the same port twice in the docker-compose: once in the expose section of the service itself and once as an environment variable in the service that connects to it. Is there a more DRY way of discovering the exposed port?


Solution

  • For this, you usually use a registrator + service-discover, this means, a service like https://www.consul.io / registrator

    Basically, this adds an API for you to either watch a kv store for you service defintions ( port / ip ) which then can be random, or even use DNS included in consul. The latter wont help with ports, thats what you use a registry for.

    If you want to dodge this best-practice way. mount the docker socket and use docker inspect <servicename> to find the port.

    services:
      other:
        container_name: foo
        image: YYYY
      theonedoingthelookup:   
        image: ZZZZ
        volumes:
          - /var/run/docker.sock:/var/run/docker.sock
    

    You will need to have the docker cli tool installed in the container, then run this inside the ZZZZ container

    docker inspect YYYY

    Use some grep / awk / filters to extract the information you need