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

383 views Asked by At

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?

2

There are 2 answers

0
Eugen Mayer On BEST ANSWER

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

3
johnharris85 On

It's whatever port the service is running as in the container. Port mappings don't apply to container <-> container communication, only host <-> container communication.

For example:

version: '2'

services:
  a:
    ...
    networks:
    - my-net
  b:
    ...
    networks:
    - my-net
networks:
  my-net:

Let's say a is running a webserver at port 8080, b would be able to hit it by sending a request to a:8080.