I also had the similar issue when I was trying to run replica set using the docker compose, I was not able to connect to the database,

This worked out for me, I added this into the /etc/hosts file

127.0.0.1       mongo1
127.0.0.1       mongo2
127.0.0.1       mongo3

then connected using
mongodb://root:example@mongo1,mongo2,mongo3/?replicaSet=rs0