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

I think the correct answer is from

Aliases can be defined as part of the network declaration for a service. See aliases in Compose file reference for more details on that. – King Chung Huang Apr 24 '17 at 15:18

here is the example from the doc

version: '2'

services:
  web:
    build: ./web
    networks:
      - new

worker:
  build: ./worker
  networks:
    - legacy

db:
  image: mysql
  networks:
    new:
      aliases:
        - database
    legacy:
      aliases:
        - mysql

networks:
  new:
  legacy:

you can access the db in this docker-compose, also you can use mysql to connect this db


extra_hosts did the trick for me.

extra_hosts:
    - "hostname:127.0.0.1"

From the docker-compose docs:

extra_hosts Add hostname mappings. Use the same values as the docker client --add-host parameter.

extra_hosts: - "somehost:162.242.195.82" - "otherhost:50.31.209.229" An entry with the ip address and hostname will be created in /etc/hosts inside containers for this service, e.g:

162.242.195.82 somehost 50.31.209.229 otherhost


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/.