Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 741
galusben Avatar asked Apr 24 '17 04:04

galusben


3 Answers

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

like image 129
King Chung Huang Avatar answered Nov 15 '22 03:11

King Chung Huang


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

like image 24
penny chan Avatar answered Nov 15 '22 04:11

penny chan


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

like image 19
galusben Avatar answered Nov 15 '22 03:11

galusben