Hey folks, I'm dealing with a frustrating issue while trying to connect to a MongoDB instance running in a Docker container from another Docker container on the same VPS. The MongoDB container is set up and accessible externally, but when I try to connect from another container, I keep hitting the error: `MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017`. I've tried various connection strings like `mongodb://username:[email protected]:27017`, `mongodb://username:[email protected]:27017`, `mongodb://username:password@localhost:27017`, and even using the VPS's IP address. I verified that UFW rules are set correctly to allow connections to port 27017, so I'm stumped. Any ideas on what could be going wrong?
2 Answers
You should connect using the MongoDB container's name as the hostname, not localhost or 127.0.0.1. When you're inside a container, those point back to itself rather than the host. `0.0.0.0` is a broad term for all IPs and won't work here. Just use the container name in your MongoDB URI. Also, double-check what 'ipaddress' you're trying; it might not be right either.
It sounds like you might need to use Docker Compose for this setup. It's not absolutely necessary, but it simplifies things a lot. With Docker Compose, you can reference your MongoDB service by its name in the other container. If you prefer not to use Compose, ensure both containers share the same Docker network. You’ll need to create a network and start both containers with the `--net` flag, ensuring MongoDB is running first before the other container tries to connect. However, using Compose makes it much more straightforward.
Could you give me a quick layout for a Docker Compose file? Here’s what I have currently for my MongoDB container setup, but I'm unsure how to adjust it for the second method. If I create both containers under the same network, will that expose my database to outside traffic?
I tried using the Docker name, but I still got the same connection error. Just to clarify, 'ipaddress' refers to my VPS's IP where the MongoDB container is running.