Many thanks for this!

I also found another working solution here:

By user Sydney.

It says:

Adding the hostnames to the hosts file did not work for me. I think if all hostnames refers to the same host IP (e.g. 127.0.0.1), it's not going to work if all docker ports are the same (e.g. 27017). The replica set is composed by  `mongo1:27017, mongo2:27017 and mongo3:27017`  inside docker. Outside docker it corresponds to  `127.0.0.1:27017, 127.0.0.1:27017 and 127.0.0.1:27017` which won't work. To fix the issue I had to set a different port for each node.

```
docker network create mongo-cluster
docker run --name mongo1 -d --net mongo-cluster -p 9042:9042 mongo:3.6 mongod --replSet docker-rs --port 9042
docker run --name mongo2 -d --net mongo-cluster -p 9142:9142 mongo:3.6 mongod --replSet docker-rs --port 9142
docker run --name mongo3 -d --net mongo-cluster -p 9242:9242 mongo:3.6 mongod --replSet docker-rs --port 9242
docker exec -it mongo1 mongo --port 9042
config = {"_id" : "docker-rs", "members" : [{"_id" : 0,"host" : "mongo1:9042"},{"_id" : 1,"host" : "mongo2:9142"},{"_id" : 2,"host" : "mongo3:9242"}]}
rs.initiate(config)
rs.status() 
```

and finally add the hostnames to the hosts file

```
127.0.0.1 mongo1 mongo2 mongo3
```

I tested on 4.4.2 and it works. Anyway, I’ll go with your solution because I like it more.

However, I wonder why solution from this guy works when it uses ports 9042, 9142, 9242, but does’t work when I set 27030, 27031, 27032, for example. Or even 8042, 8142, 8242.

Do yo know why it happens?

As I said, I won’t go with this solution, but just too curios. :sweat_smile:

Thanks!