Clarification needed regarding how container & service ports made available?

Hi there,

I am experimenting with docker swarm. I ran into this issue, when I am trying to setup a mongodb cluster.
I created a swarm of 3 nodes. I have launched 3 mongodb services(mongo1, mongo2, mongo3) in each of the nodes. All the services are in same network called mongo. I am not able to connect to any other mongo service from an another mongo service.

docker exec -it $mongo_client mongo mongo1/foo
docker exec -it $mongo_client mongo mongo2/foo
docker exec -it $mongo_client mongo mongo3/foo

The above mongo commands are failing to connect. Based on the error messages, I came to know that, each of the hostnames mongo1, mongo2, mongo3 are resolving correctly. I am able to see the ip address in the error messages as, &

Sample error:

MongoDB shell version: 3.2.21
connecting to: mongo3/foo
2018-12-20T02:45:05.042+0000 W NETWORK  [thread1] Failed to connect to, in(checking socket for error after poll), reason: errno:111 Connection refused
2018-12-20T02:45:05.043+0000 E QUERY    [thread1] Error: couldn't connect to server mongo3:27017, connection attempt failed :

exception: connect failed

I am not able to understand the reason. I am able to connect to the mongo from the same container on port 27017, it works. But, when I tried to connect using, it failed.

May be the mongod is listening only on localhost address. I followed this article. In that, it is mentioned as the connection to mongo is based on the service name. If the mongod to be listened on any other port, it would have gotten mentioned in the article.


I checked the IP address of the container running the mongod. It is, while service name of the same is resolved to I am able to see the difference between the container IP & service IP.
I tried to connect to the mongod using the IP of the container from another container in the same network and it worked.

This shows that containers in the same overlay network are able to communicate to each other using IP address. But, how to use service name to connect to the mongod?

Any clarification on this issue would be appreciative.