I've created one Dockerfile of mongodb, given below.
FROM mongo
COPY ./start.sh .
RUN chmod +x ./start.sh
EXPOSE 27017-27019
CMD ["./start.sh"]
start.sh contains the below content
mongod
The Command I'm using to run docker
sudo docker run -p 27017:27017 custom_mongo
I'm able to connect this docker from inside the container (i.e. by the exec -it command and then using the mongo client ) but, when trying to connect from Mongo Compass it's timing out, meaning the port are not forwarded/exposed.
The equivalent docker, when running directly without any Dockerfile, is successfully connecting to Compass. The command is given below that I've used.
docker run -d -p 27017-27019:27017-27019 --name mongodb mongo
So, the problem was that the mongod command in the start.sh was listening to 127.0.0.1 i.e. localhost which is accessible only from inside the container not outside.
For the container to listen to the outside hosts, it should be connected to 0.0.0.0 which means any IP. So to enable that , edit the startup command to mongod --bind_ip_all.
Reference : https://forums.docker.com/t/docker-running-host-but-not-accessible/44082/48