How to allow docker containers to see each other by their name?

I have a mongo instance running in a container named mongo1 that has exposed port 27017. I can connect just fine from the host.

I have another container that is running an application that wants to connect to the mongo instance.

How can I connect the 2 containers so that the hostname mongo1 is exposed to the other container and it can connect to mongo1:27017 ?

What was happening was that the default docker network doesn't allow name >> DNS mapping.

Containers on the default bridge network can only access each other by IP addresses, unless you use the --link option, which is considered legacy. On a user-defined bridge network, containers can resolve each other by name or alias.

So I created a new network:

docker network create -d bridge br0

and then added the containers to that network:

docker network connect br0 mongo1
docker network connect br0 wiki

now they can see each other by their name.

For existing containers (as Temporary solution)

docker inspect <mango_container_name> | grep IPAddress

and edite/add /etc/hosts inside the container

docker exec -it -u 0 <app_container_name> bash

then from inside the container map container_name with the IP address .. Example

echo "172.15.0.5 mango1" >> /etc/hosts

exit

.......
Or you can assign hostname for container during spining it up with

docker run -it -h mango1 mango_image

and/or add Example echo "172.17.0.5 mango1" >> /etc/hosts command in docker files for less headache