In docker-compose, how do I create an alias / link to localhost?
In my docker compose file, I need multiple containers to know the hostname of a particular container, including that particular container.
Links will not work as the container cannot reference itself.
Basically what I'm looking for is a way to create a localhost alias in docker-compose.
source to share
You should avoid using links. Instead, services on the same Docker network can find each other using service names as DNS names. Use this to refer to a specific container that you described, including when it references itself.
For example, in the following compiled Docker Compose, if there someservice
was a webserver serving port 80, the service anotherservice
could connect to it at the address http://someservice/
because they are on a shared 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 in http://someservice/
.
source to share
extra_hosts helped.
extra_hosts: - "hostname: 127.0.0.1"
From the docker-compose docs:
extra_hosts Add hostname mapping. Use the same values as docker client --add-host.
extra_hosts: - "somehost: 162.242.195.82" - "otherhost: 50.31.209.229" An entry with IP address and hostname will be created in / etc / hosts inside containers for this service, for example:
162.242.195.82 somehost 50.31.209.229 otherhost
source to share
I think the correct answer is from
Aliases can be defined as part of an online advertisement for a service. See the aliases in the Compose file link for more information on this. - King Chung Huang on April 24, 17 at 15:18
here is an 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 db
in this docker-compose, also you can use mysql
to connect thisdb
source to share