dockerdocker-compose

In docker-compose how to create an alias / link to localhost?


In my docker-compose file there is a need for several containers to know the hostname of a specific container, including this specific container.

Links will not work, since a container can not link to itself.

Basically, what I am looking for is a way to alias localhost in docker-compose.


Solution

  • You should avoid using links. Instead, services on the same Docker network can find each other by using service names as DNS names. Use that to reference the specific container you described, including when it references itself.

    For example, in the following made up Docker Compose file, if someservice was a web server serving on port 80, anotherservice service would be able to connect to it at http://someservice/, because they're on a common network the_net.

    version: '3'
    
    services:
      someservice:
        image: someserviceimage
        networks:
          - the_net
    
      anotherservice:
        image: anotherserviceimage
        networks:
          - the_net
    
    networks:
      the_net:
    

    someservice can also reach itself at http://someservice/.